<?php

class ControllerQuickCheckoutCart extends Controller {

    public function index() {
        $data = $this->load->language('checkout/checkout');
        $data = array_merge($data, $this->load->language('quickcheckout/checkout'));

        /**
         * 02.09.20 check promotions and coupon, if there is return coupon, delete it (ali a.)
         */
        $this->load->model('checkout/coupon');

        if (isset($this->session->data['campaign_price_total'])
            && isset($this->session->data['coupon']) && $this->model_checkout_coupon->isReturnCoupon($this->session->data['coupon']) === true) {

            unset($this->session->data['coupon']);
            $data['error_warning'] = 'Bu kupon promosyon ile kullanılamaz';
        }
        /**
         * end of update (ali a.)
         */

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

        $total_data = array();
        $total = 0;
        $taxes = $this->cart->getTaxes();

        $total_data = array(
            'totals' => &$totals,
            'taxes' => &$taxes,
            'total' => &$total
        );

        // Display prices
        $data['totals'] = array();

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

            $results = $this->model_extension_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('extension/total/' . $result['code']);

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

            $total_data = $totals;

            $sort_order = array();

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

            array_multisort($sort_order, SORT_ASC, $total_data);

            foreach ($total_data as $total) {
                $text = $this->currency->format($total['value'], $this->session->data['currency']);

                $data['totals'][] = array(
                    'title' => $total['title'],
                    'text' => $text
                );
            }
        }

        /**
         * Sepet Toplamına Göre Puan Hesaplayıcı
         * -Can Yiğit KAV
         * 30.03.2022
         */
        $reward_setting_status = $this->config->get('reward_setting_status');            
        $data['reward_total'] = false;
        if($reward_setting_status) {
            $reward_setting_percent = $this->config->get('reward_setting_percent');
            $reward_setting_total_status = $this->config->get('reward_setting_total_status');            
            $reward_setting_total_text = $reward_setting_total_status==1 ? 'total' : 'sub_total'; 
            foreach($total_data as $total) {
                if($total['code'] == $reward_setting_total_text) {
                    $reward_total = $total['value']/100*$reward_setting_percent;
                    $reward_total = number_format($reward_total, 2, ',', '');
                    $data['reward_total'] = "Üyeliğinle tamamlayacağın bu siparişte ". $reward_total ."₺ değerinde Deercase Puan kazanacaksın!";
                }
            }
        }            
        # /Sepet Toplamına Göre Puan Hesaplayıcı

        $this->load->model('tool/image');
        $this->load->model('tool/upload');
        $this->load->model('catalog/product');
        $data['products'] = array();

        $products = $this->cart->getProducts();


        foreach ($products as $product) {
            $product_total = 0;

            foreach ($products as $product_2) {
                if ($product_2['product_id'] == $product['product_id']) {
                    $product_total += $product_2['quantity'];
                }
            }

            if ($product['minimum'] > $product_total) {
                $data['error_warning'] = sprintf($this->language->get('error_minimum'), $product['name'], $product['minimum']);
            }

            if ($product['image']) {
                $image = $this->model_tool_image->resize($product['image'], $this->config->get($this->config->get('config_theme') . '_image_cart_width'), $this->config->get($this->config->get('config_theme') . '_image_cart_height'));
            } else {
                $image = '';
            }

            $option_data = array();

            foreach ($product['option'] as $option) {
                if ($option['type'] != 'file') {
                    $value = $option['value'];
                } else {
                    $upload_info = $this->model_tool_upload->getUploadByCode($option['value']);

                    if ($upload_info) {
                        $value = $upload_info['name'];
                    } else {
                        $value = '';
                    }
                }

                $option_data[] = array(
                    'name' => $option['name'],
                    'value' => $value
                );

            }



            // Display prices
            if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
                $price = $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
            } else {
                $price = false;
            }

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

            $recurring = '';

            if ($product['recurring']) {
                $frequencies = array(
                    'day' => $this->language->get('text_day'),
                    'week' => $this->language->get('text_week'),
                    'semi_month' => $this->language->get('text_semi_month'),
                    'month' => $this->language->get('text_month'),
                    'year' => $this->language->get('text_year'),
                );

                if ($product['recurring']['trial']) {
                    $recurring = sprintf($this->language->get('text_trial_description'), $this->currency->format($this->tax->calculate($product['recurring']['trial_price'] * $product['quantity'], $product['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']), $product['recurring']['trial_cycle'], $frequencies[$product['recurring']['trial_frequency']], $product['recurring']['trial_duration']) . ' ';
                }

                if ($product['recurring']['duration']) {
                    $recurring .= sprintf($this->language->get('text_payment_description'), $this->currency->format($this->tax->calculate($product['recurring']['price'] * $product['quantity'], $product['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']), $product['recurring']['cycle'], $frequencies[$product['recurring']['frequency']], $product['recurring']['duration']);
                } else {
                    $recurring .= sprintf($this->language->get('text_payment_cancel'), $this->currency->format($this->tax->calculate($product['recurring']['price'] * $product['quantity'], $product['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']), $product['recurring']['cycle'], $frequencies[$product['recurring']['frequency']], $product['recurring']['duration']);
                }
            }
            $customcase_image = $case_image = '';
           
            if ($product['customcase_image'] != '') {
                $str = explode('***', $product['customcase_image']);
                $customcase_image = ($this->request->server['HTTPS'] ? HTTPS_SERVER : HTTP_SERVER) . 'image/' . $str[1];
                $case_image = ($this->request->server['HTTPS'] ? HTTPS_SERVER : HTTP_SERVER) . 'image/' . $product['image'];
            }
            $product_type = $this->model_catalog_product->getProduct_type($product['product_id']);
            if ($product_type==11||$product_type==12) {
                $ppp=$product['p_11_pattern_img'];
                if($ppp==""){
                    $ppp=$str = explode('***', $product['customcase_image'])[1];
                }
                $customcase_image=$this->model_catalog_product->get_c_blob($ppp);
                $customcase_image='data:image;base64,'.($customcase_image);
            }
            $data['products'][] = array(
                'key' => isset($product['key']) ? $product['key'] : $product['cart_id'],
                'thumb' => $image,
                'name' =>  $product['name'],
                'product_type' => $product_type,
                'customer_order_image' => ($this->request->server['HTTPS'] ? HTTPS_SERVER : HTTP_SERVER) . 'image/' . $product['customer_order_image'],
                'customcase_image' => $customcase_image,
                'case_image' => $case_image,
                'model' => $product['model'],
                'option' => $option_data,
                'recurring' => $recurring,
                'quantity' => $product['quantity'],
                'stock' => $product['stock'] ? true : !(!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning')),
                'reward' => ($product['reward'] ? sprintf($this->language->get('text_points'), $product['reward']) : ''),
                'price' => $price,
                'total' => $total,
                'href' => $this->url->link('product/product', 'product_id=' . $product['product_id'])
            );
        }

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

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

        // All variables
        $data['edit_cart'] = $this->config->get('quickcheckout_edit_cart');

        if (file_exists(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/quickcheckout/cart.tpl')) {
            $this->response->setOutput($this->load->view(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/quickcheckout/cart', $data));
        } else {
            $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'default/template/quickcheckout/cart', $data));
        }
    }

    public function update() {
        $json = array();

        if (!empty($this->request->post['quantity'])) {
            if ($this->config->get('advertisement_system_status') && count($this->request->post['quantity']) == 1) {
                $products = $this->cart->getProducts();
                if ($products[0]['product_id'] == $this->config->get('advertisement_product_id')) {
                    $this->load->language('account/mpadvertisement');
                    $this->session->data['warning'] = $this->language->get('error_quantity');
                    $this->response->redirect($this->url->link('account/mpadvertisement'));
                }
            }
            foreach ($this->request->post['quantity'] as $key => $value) {
                $this->cart->update($key, $value);
            }
        }

        if (isset($this->request->get['remove'])) {
            $this->cart->remove($this->request->get['remove']);
            
            unset($this->session->data['vouchers'][$this->request->get['remove']]);
        }

        if ((!$this->cart->hasProducts() && empty($this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
            $json['redirect'] = $this->url->link('checkout/cart');
        }

        if ($this->cart->getTotal() < $this->config->get('quickcheckout_minimum_order')) {
            $json['redirect'] = $this->url->link('checkout/cart');
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

}
