<?php

class ControllerModuleCart extends Controller
{
    public function index()
    {
        $this->language->load('module/cart');
        $this->load->helper('ftr_geral');

        $checkLastRoute = isset($_SERVER['HTTP_REFERER']) && (strpos($_SERVER['HTTP_REFERER'], 'checkout/cart') !== false || strpos($_SERVER['HTTP_REFERER'], 'checkout/checkout') !== false);
        $floatingCartLayout = strpos($_SERVER['REQUEST_URI'], 'module/cart') !== false;

        $this->data['isCartPage'] = $checkLastRoute && $floatingCartLayout;

        $this->data['futuragrade_status'] = $this->config->get('futuragrade_status');

        if (isset($this->request->get['remove'])) {
            $this->cart->remove($this->request->get['remove']);

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

            if ($this->config->get('listapresente_status')) {
                if (isset($this->session->data['cartxitem'])) {
                    $this->presente->remove((int) $this->request->get['remove']);
                    if ($this->cart->getTotal() == 0) {
                        unset($this->session->data['cartxitem']);
                    }
                }
            }
        }

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

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

        // Display prices
        if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
            $sort_order = array();

            $results = $this->model_setting_extension->getExtensions('total');

            foreach ($results as $key => $value) {
                $sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
            }

            array_multisort($sort_order, SORT_ASC, $results);

            foreach ($results as $result) {
                if ($this->config->get($result['code'] . '_status')) {
                    $this->load->model('total/' . $result['code']);

                    $this->{'model_total_' . $result['code']}->getTotal($total_data, $total);
                }

                $sort_order = array();

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

                array_multisort($sort_order, SORT_ASC, $total_data);
            }
        }

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

        $countProducts = $this->cart->countProducts();

        $this->data['text_items'] = sprintf($this->language->get('text_items'), $countProducts + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0), $this->currency->format($total));
        $this->data['text_items_cart_sus'] = sprintf($this->language->get('text_items_sus'), $countProducts + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0));
        $this->data['qtd_items'] = $countProducts;
        $this->data['text_empty'] = $this->language->get('text_empty');
        $this->data['text_cart'] = $this->language->get('text_cart');
        $this->data['text_checkout'] = $this->language->get('text_checkout');
        $this->data['text_payment_profile'] = $this->language->get('text_payment_profile');
        $text_separator_grade = (ftr_geral::isIsset($this->config->get('futuragrade_abrev_title_specification')) && $this->config->get('futuragrade_abrev_title_specification') != "") ? ucfirst(strtolower($this->config->get('futuragrade_abrev_title_specification'))) : $this->language->get('text_specification_description');
        $this->data['text_specification_description'] = sprintf($this->language->get('text_separator_grade'), $text_separator_grade);
        $this->data['button_remove'] = $this->language->get('button_remove');

        $this->load->dmodel('tool/image');

        $this->data['cartList'] = array();

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

        $products = array_slice(array_reverse($this->cart->getProducts()), 0, 4);
        $variedadesCart = $this->cart->countVariedadeProducts();
        if ($variedadesCart > 4) {
            $this->data['itens_cart_restantes'] = $variedadesCart - 4;
        }

        foreach ($products as $product) {
            if ($product['image']) {
                $watermark_config_date_number = $this->dmodel_tool_image->getWatermarkCacheNumber();
                $image_version_number = '?version=' . preg_replace("/[^0-9]/", "", $product['data_atualizacao_replicacao']) . $watermark_config_date_number;
                $image = $this->dmodel_tool_image->resizeWithWatermark($product['image'], Type_MiniatureMedium::Tp_width, Type_MiniatureMedium::Tp_height) . $image_version_number;
            } else {
                $image = $this->dmodel_tool_image->resize('data/sem-imagem.png', Type_MiniatureMedium::Tp_width, Type_MiniatureMedium::Tp_height);
            }

            $option_data = array();

            $this->load->model('catalog/product');

            foreach ($product['option'] as $option) {
                if ($option['type'] != 'file') {
                    $value = $option['option_value'];
                } else {
                    $filename = $this->encryption->decrypt($option['option_value']);

                    $value = utf8_substr($filename, 0, utf8_strrpos($filename, '.'));
                }

                $option_data[] = array(
                    'name' => $option['name'],
                    'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value),
                    'type' => $option['type']
                );
            }

            // Display prices
            if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
                $price = $this->currency->format($product['price']);
            } else {
                $price = false;
            }

            // Display prices
            if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
                $total = $this->currency->format($product['price'] * $product['quantity']);
            } else {
                $total = false;
            }

            $gridhaveid = false;
            if ($this->config->get('futuragrade_status')) {
                $gridhaveid = $this->model_catalog_product->getGridHave($product['product_id'])['grid_id'];
            }

            $this->data['cartList'][] = array(
                'grid_id' => $gridhaveid,
                'color_description' => ($this->config->get('futuragrade_status')) ? $product['color_description'] : '',
                'size_description' => ($this->config->get('futuragrade_status')) ? $product['size_description'] : '',
                'specification_description' => ($this->config->get('futuragrade_status')) ? $product['specification_description'] : '',
                'key' => $product['key'],
                'thumb' => $image,
                'name' => html_entity_decode($product['name']),
                'model' => $product['model'],
                'option' => $option_data,
                'quantity' => $product['quantity'],
                'price' => $price,
                'stock' => $product['stock'] ? true : !(!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning')),
                'total' => $total,
                'href' => $this->url->link('product/product', 'product_id=' . $product['product_id']),
                'recurring' => $product['recurring'],
                'profile' => $product['profile_name'],
                'isListaEscolar' => (isset($product['lista_escolar_id']) && $product['lista_escolar_id'] > 0) ? true : false,
            );
        }

        // Gift Voucher
        $this->data['vouchers'] = array();

        if (!empty($this->session->data['vouchers'])) {
            foreach ($this->session->data['vouchers'] as $key => $voucher) {
                $this->data['vouchers'][] = array(
                    'key' => $key,
                    'description' => $voucher['description'],
                    'amount' => $this->currency->format($voucher['amount'])
                );
            }
        }

        $this->data['cart'] = $this->url->link('checkout/cart');

        if ($this->customer->isLogged()) {
            $this->data['checkout'] = $this->url->link('checkout/information', '', 'SSL');
        } else {
            $this->data['checkout'] = $this->url->link('checkout/checkout', '', 'SSL');
        }

        $this->response->setOutput($this->render('module/cart'));
    }

}
