<?php
$loader = $this->registry->get('load');
$loader->controller('checkout/cart');

class ControllerFidelityCart extends ControllerCheckoutCart
{
    private $error = array();
    protected $referencePathFile = 'fidelity/cart';
    protected $cartName = 'fidelitycart';
    protected $fileName;
    protected $pathName;

    public function index($cartList = false)
    {
        $this->isLogged();
        parent::index();
    }

    public function getEmptyCart()
    {
        $this->language->load($this->referencePathFile);

        $this->data['heading_title'] = $this->language->get('heading_title');

        $this->data['text_error'] = $this->language->get('text_empty');

        $this->data['button_continue'] = $this->language->get('button_continue');

        $this->data['continue'] = $this->url->link('common/home', '', 'NONSSL', 'false');

        unset($this->session->data['success']);

        if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/error/not_found.tpl')) {
            $this->template = $this->config->get('config_template') . '/template/error/not_found.tpl';
        } else {
            $this->template = 'default/template/error/not_found.tpl';
        }

        $this->children = $this->getChildren();

        if (isset($this->request->get['ajax']) && $this->request->get['ajax']) {
            $this->response->setOutputJson($this->data);
        } else {
            $this->response->setOutput($this->render('error/not_found'));
        }
    }

    public function getChildren($data = null)
    {
        $children = array(
            'common/breadcrumbs',
            'common/column_left',
            'common/column_right',
            'common/content_top',
            'common/content_bottom',
            'common/footer',
            'common/header'
        );
        if ($data !== null) {
            array_push($children, $data);
        }
        return $children;
    }


    public function add($dataListColor = false)
    {

        $json = array();
        $this->language->load($this->referencePathFile);


        $this->load->model('catalog/product');
        $this->load->type('tipocomum');
        $errorGrade = false;

        if (isset($this->request->post['product_id'])) {
            $product_id = $this->request->post['product_id'];
        } else {
            $product_id = 0;
        }

        $product_info = $this->model_catalog_product->getProduct($product_id);
        if ($product_info) {

            if (!$this->customer->isLogged()) {
                $json['error']['logged'] = sprintf($this->language->get('text_logged'), $this->url->link('account/register'));
            }

            if ($product_info['pontos'] > $this->customer->getPoints() && $this->customer->isLogged()) {
                $json['error']['quantity'] = 'Você não possui pontos para trocar por esse produto';
            }

            if (($product_info['pontos'] + $this->{$this->cartName}->getTotal()) > $this->customer->getPoints()) {
                //$json['error']['quantity'] = 'Você não possui pontos para trocar por esse produto';
            }

            if (isset($this->request->post['quantity'])) {
                $quantity = $this->request->post['quantity'];
                if ($quantity == '' || $quantity <= 0) {
                    $json['error']['quantity'] = 'Atenção: Não é possivél adicionar produtos sem quantidade!';
                }
                if (!$this->config->get('config_stock_checkout') && $quantity != '' && (($this->{$this->cartName}->getItemQuantity($product_id) + $quantity) > $product_info['qty'])) {
                    $json['error']['quantity_indisponivel'] = 'Atenção: Quantidade solicitada indisponível em nosso estoque!';
                }
            } else {
                $quantity = 1;
            }


            if ($this->config->get('futuragrade_status')) {
                $gridhave = $this->model_catalog_product->getGridHave($product_id);
                if (!isset($this->request->get['size_id'])) {
                    if ($gridhave['have_size']) {
                        $json['error']['grid_size'] = 'Por favor, informe um(a) ' . $gridhave['template_tamanho'] . '!';
                        $errorGrade = true;
                    }
                }
                if (!isset($this->request->get['specification_id'])) {
                    if ($gridhave['have_specification']) {
                        $json['error']['grid_specification'] = 'Por favor, informe um(a) ' . $gridhave['template_especificacao'] . '!';
                        $errorGrade = true;
                    }
                }
            }

            if (!$json) {
                $this->{$this->cartName}->add($product_id, $quantity, $option = array());
                $json['redirect'] = str_replace('&amp;', '&', $this->url->link($this->referencePathFile, '', 'SSL'));

                unset($this->session->data['shipping_method']);
                unset($this->session->data['shipping_methods']);
                unset($this->session->data['payment_method']);
                unset($this->session->data['payment_methods']);

                // Totals
                $this->load->model('setting/extension');

                $total_data = array();
                $total = 0;

                $json['total'] = sprintf($this->language->get('text_items'), $this->{$this->cartName}->countProducts(), $this->currency->format($total));
                $json['total_qtd'] = $this->{$this->cartName}->countProducts();
            }

            $this->load->dmodel('design/layout');
            $fidelity_id_layout = $this->dmodel_design_layout->getLayoutByName('fidelidade');
            //caso o produto seja grade e tenha que ser escolhido tamanho/cor/especificação ele redireciona para a página do produto
            if (isset($this->request->post['layout_id']) && ($this->request->post['layout_id'] == $fidelity_id_layout) && ($errorGrade)) {
                $json['redirect'] = $this->url->link('fidelity/product', 'product_id=' . $this->request->post['product_id']);
            }
        }

        $json['product_id'] = $this->request->post['product_id'];

        $this->response->setOutput(json_encode($json));
    }

    public function quoteShipping()
    {
        $this->load->controller('postcode/postcode');
        $controllerPostcode = new ControllerPostcodePostcode($this->registry);

        $postcodeSearch = $controllerPostcode->search(true);

        $zoneId = false;
        if (isset($postcodeSearch['dados']) && $postcodeSearch['dados']['zone_id'] != '') {
            $zoneId = $postcodeSearch['dados']['zone_id'];
        }

        $this->quote($zoneId);
    }

    public function quote($zone_id = false)
    {

        $zone_id = $zone_id ?? $this->request->post['zone_id'];

        $this->load->type('tipocomum');
        $this->language->load('checkout/cart');

        $json = array();
        if (!isset($this->request->post['freteproduto_id'])) {
            /*As validações abaixo são feitas para itens do carrinho, quando freteproduto_id estiver prrenchido, significa
            que o calculo está sendo chamado pela tela de produto, essas validações não devem ser feitas*/
            if (!$this->{$this->cartName}->hasProducts()) {
                $json['error']['warning'] = $this->language->get('error_product');
            }

            if (!$this->{$this->cartName}->hasShipping()) {
                $json['error']['warning'] = sprintf($this->language->get('error_no_shipping'), $this->url->link('information/contact'));
            }
        }

        if ((utf8_strlen($this->request->post['postcode']) <= 8)) {
            $json['error']['postcode'] = $this->language->get('error_postcode');
        }

        $this->load->model('localisation/country');

        $country_id = Type_PaisId::Tp_Brasil;

        $country_info = $this->model_localisation_country->getCountry($country_id);

        if ($country_info && $country_info['postcode_required'] && (utf8_strlen($this->request->post['postcode']) < 2) || (utf8_strlen($this->request->post['postcode']) > 10)) {
            $json['error']['postcode'] = $this->language->get('error_postcode');
        }

        if (!$json) {

            // Default Shipping Address
            $this->session->data['shipping_country_id'] = $country_id;
            if (isset($zone_id)) {
                $this->session->data['shipping_zone_id'] = $zone_id;
            }
            $this->session->data['shipping_postcode'] = $this->request->post['postcode'];

            if ($country_info) {
                $country = $country_info['name'];
                $iso_code_2 = $country_info['iso_code_2'];
                $iso_code_3 = $country_info['iso_code_3'];
                $address_format = $country_info['address_format'];
            } else {
                $country = '';
                $iso_code_2 = '';
                $iso_code_3 = '';
                $address_format = '';
            }

            $this->load->model('localisation/zone');

            if (isset($zone_id)) {
                $zone_info = $this->model_localisation_zone->getZone($zone_id);

                if ($zone_info) {
                    $zone = $zone_info['name'];
                    $zone_code = $zone_info['code'];
                } else {
                    $zone = '';
                    $zone_code = '';
                }
            } else {
                $zone = '';
                $zone_code = '';
            }

            $address_data = array(
                'firstname' => '',
                'lastname' => '',
                'company' => '',
                'address_1' => '',
                'address_2' => '',
                'postcode' => str_replace('-', '', $this->request->post['postcode']),
                'city' => '',
                'zone_id' => (isset($zone_id)) ? $zone_id : '',
                'zone' => $zone,
                'zone_code' => $zone_code,
                'country_id' => $country_id,
                'country' => $country,
                'iso_code_2' => $iso_code_2,
                'iso_code_3' => $iso_code_3,
                'address_format' => $address_format,
                'layout_id' => (isset($this->request->post['freteproduto_id'])) ? Type_SendPostcode::Tp_Product : Type_SendPostcode::Tp_Cart
            );

            $quote_data = array();

            $this->load->model('setting/extension');
            $results = $this->model_setting_extension->getExtensions('shipping');

            if (isset($this->request->post['freteproduto_id'])) {
                $freteproduto_id = $this->request->post['freteproduto_id'];
                $this->load->model('catalog/product');
                $product_aux = $this->model_catalog_product->getProduct($freteproduto_id);
                if (isset($product_aux['special']) && ($product_aux['special'] > 0)) {
                    $product_aux['price'] = $product_aux['special'];
                }
                //sempre referente a uma unica quantidade nesse caso...
                $product_aux['quantity'] = 1;
                $product_aux['total'] = $product_aux['price'];

                $product_info[] = $product_aux;
            }

            foreach ($results as $result) {
                if ($this->config->get($result['code'] . '_status')) {
                    $this->load->model('shipping/' . $result['code']);
                    if (isset($freteproduto_id)) {
                        $quote = $this->{'model_shipping_' . $result['code']}->getQuote($address_data, $product_info);
                    } else {
                        $quote = $this->{'model_shipping_' . $result['code']}->getQuote($address_data);
                    }
                    if ($quote) {
                        $quote_data[$result['code']] = array(
                            'title' => $quote['title'],
                            'quote' => $quote['quote'],
                            'sort_order' => $quote['sort_order'],
                            'error' => $quote['error']
                        );
                    }
                }
            }

            $sort_order = array();

            foreach ($quote_data as $key => $value) {
                $sort_order[$key] = $value['sort_order'];
            }

            array_multisort($sort_order, SORT_ASC, $quote_data);

            $this->session->data['shipping_methods'] = $quote_data;

            if ($this->session->data['shipping_methods']) {
                $json['shipping_method'] = $this->session->data['shipping_methods'];
            } else {
                $json['error']['warning'] = sprintf($this->language->get('error_no_shipping'), $this->url->link('information/contact'));
            }
        }

        $this->response->setOutput(json_encode($json));
    }

    public function loadScript()
    {

        $this->document->addScript(array(
            'catalog/view/theme/vista/public/js/fidelity/cart.js',
        ));

        if ($this->ftrgeralregistry->isApp()) {
            $this->document->addScriptApp(array(
                'catalog/view/theme/appmobile/public/js/page.cart.js',
                'catalog/view/theme/appmobile/public/js/jquery.mask.js',
            ));
        }
    }

    public function redirectAjax()
    {
        $args = $this->isAjax ? 'ajax=1' : '';
        $link = $this->url->link($this->referencePathFile, $args);

        $this->redirect($link);
    }

    public function quantity()
    {
        foreach ($this->request->post['quantity'] as $key => $value) {
            if ($this->config->get('config_stock_checkout')) {
                $this->{$this->cartName}->update($key, $value);
            } else {
                $result = $this->model_catalog_product->getProduct($key);
                if ($result['qty'] >= $value) {
                    $this->{$this->cartName}->update($key, $value);
                    // $this->session->data['success'] = 'Quantidade alterada com sucesso!';
                } else {
                    $this->session->data['warning'] = $this->language->get('error_stock_product');
                }
            }
        }

        unset($this->session->data['shipping_method']);
        unset($this->session->data['shipping_methods']);
        unset($this->session->data['payment_method']);
        unset($this->session->data['payment_methods']);
        unset($this->session->data['reward']);

        $this->redirectAjax($this->isAjax);
    }


    public function isLogged()
    {
        if (!$this->customer->isLogged()) {
            $this->session->data['redirect'] = $this->url->link('account/address', '', 'SSL');
            $this->redirect($this->url->link('account/register', '', 'SSL'));
        }
    }

    public function remove($cartList)
    {
        $this->{$this->cartName}->remove($this->request->get['remove']);

        unset($this->session->data['vouchers'][$this->request->get['remove']]);

        if($cartList) {
            $this->session->data['success'] = $this->language->get('text_remove');
        }
        unset($this->session->data['shipping_method']);
        unset($this->session->data['shipping_methods']);
        unset($this->session->data['payment_method']);
        unset($this->session->data['payment_methods']);
        unset($this->session->data['reward']);

        $this->redirectAjax($this->isAjax);
    }

    public function extraActions()
    {
    }

    public function breadcrumbs()
    {
        $this->data['breadcrumbs'] = array();

        $this->data['breadcrumbs'][] = array(
            'href' => $this->url->link('common/home', '', 'NONSSL', 'false'),
            'text' => $this->language->get('text_home'),
            'separator' => false
        );

        $this->data['breadcrumbs'][] = array(
            'href' => $this->url->link('fidelity/category', '', 'NONSSL', 'true'),
            'text' => 'Resgatar Pontos',
            'separator' => $this->language->get('text_separator')
        );

        $this->data['breadcrumbs'][] = array(
            'href' => $this->url->link($this->referencePathFile),
            'text' => $this->language->get('heading_title'),
            'separator' => $this->language->get('text_separator')
        );

        $this->breadcrumbs->setbreadcumbs($this->data['breadcrumbs']);
    }

    public function rewards()
    {
    }

    public function messages()
    {

        if ($this->config->get('config_customer_price') && !$this->customer->isLogged()) {
            $this->data['attention'] = sprintf($this->language->get('text_login'), $this->url->link('account/register'), $this->url->link('account/register'));
        } else {
            $this->data['attention'] = '';
        }
    }

    public function getCartListAdditionalInfo($info)
    {
        extract($info);
        return [
            'href' => $this->url->link('fidelity/product', 'product_id=' . $product['product_id']),
            'pontos' => $product['pontos'],
        ];
    }

    public function productExtraActions($info)
    {
        extract($info);

        $total = ($product['pontos'] * $product['quantity']);
        $tipoLista = Type_ProductCart::Tp_Default;
        $id_lista = 0;
        return [
            'product' => $product,
            'id_lista' => $id_lista,
            'tipoLista' => $tipoLista,
            'total' => $total
        ];
    }

    public function extraActionsEnd($products, $isAjax = false)
    {
        $totals = array(
            'pontoscart' => array(
                'title' => 'Pontos a trocar',
                'text' => $this->{$this->cartName}->getTotal() . ' pontos'
            ),
            'pontoscustomer' => array(
                'title' => 'Seus Pontos',
                'text' =>  $this->customer->getPoints() . ' pontos'
            ),
            'pontosgeral' => array(
                'title' => 'Pontos restantes',
                'text' => ($this->customer->getPoints() - $this->{$this->cartName}->getTotal()) . ' pontos'
            )
        );

        $this->data['totals'] = $totals;

        $this->data['disabled_checkout'] = false;

        if (isset($this->error['warning'])) {
            $this->data['error_warning'] = $this->error['warning'];
        } elseif (!$this->{$this->cartName}->hasStock() && (!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning'))) {
            $this->data['error_warning'] = $this->language->get('error_stock');
        } elseif ($this->{$this->cartName}->getTotal() > $this->customer->getPoints()) {
            $this->data['error_warning'] = 'Você não possui pontos para finalizar a troca, remova algum(s) produto(s) antes de continuar!';
            $this->data['disabled_checkout'] = true;
        } else {
            if (isset($this->session->data['warning'])) {
                $this->data['error_warning'] = addslashes($this->session->data['warning']);
                unset($this->session->data['warning']);
            } else {
                $this->data['error_warning'] = '';
            }
        }

        if (isset($this->session->data['success'])) {
            $this->data['success'] = addslashes($this->session->data['success']);

            unset($this->session->data['success']);
        } else {
            $this->data['success'] = '';
        }

        $this->data['checkout'] = $this->url->link('fidelity/checkout', '', 'SSL');
        $this->data['action'] = $this->url->link($this->referencePathFile);

        $this->children = $this->getChildren();
    }
}
