<?php
require_once DIR_SYSTEM . "library" . DIRECTORY_SEPARATOR . "iyzico" . DIRECTORY_SEPARATOR . "IyzipayBootstrap.php";

class ControllerCheckoutOdeme extends Controller {

    //private $base_url = "https://api.iyzipay.com";
    private $base_url = "https://sandbox-api.iyzipay.com";
    private $order_prefix = "PSIYZICO_";
    private $valid_currency = array("TRY", "GBP", "USD", "EUR", "IRR");
    private $iyzico_version = "v5";

    public function index()
    {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Headers: *");

        $this->load->language('checkout/checkout');
        $this->document->setTitle($this->language->get('heading_title'));

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

        $data['text_checkout_option'] = sprintf($this->language->get('text_checkout_option'), 1);
        $data['text_checkout_account'] = sprintf($this->language->get('text_checkout_account'), 2);
        $data['text_checkout_payment_address'] = sprintf($this->language->get('text_checkout_payment_address'), 2);
        $data['text_checkout_shipping_address'] = sprintf($this->language->get('text_checkout_shipping_address'), 3);
        $data['text_checkout_shipping_method'] = sprintf($this->language->get('text_checkout_shipping_method'), 4);

        if ($this->cart->hasShipping()) {
            $data['text_checkout_payment_method'] = sprintf($this->language->get('text_checkout_payment_method'), 5);
            $data['text_checkout_confirm'] = sprintf($this->language->get('text_checkout_confirm'), 6);
        } else {
            $data['text_checkout_payment_method'] = sprintf($this->language->get('text_checkout_payment_method'), 3);
            $data['text_checkout_confirm'] = sprintf($this->language->get('text_checkout_confirm'), 4);
        }


        if ($this->request->server['HTTPS']) {
            $server = $this->config->get('config_ssl');
        } else {
            $server = $this->config->get('config_url');
        }

        if (is_file(DIR_IMAGE . $this->config->get('config_logo'))) {
            $data['logo'] = $server . 'image/' . $this->config->get('config_logo');
        } else {
            $data['logo'] = '';
        }

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

    }

    public function isLogin()
    {
        //https://www.deercase.com/index.php?route=checkout/odeme/isLogin

        $param = array_merge($_POST, (array) json_decode(file_get_contents('php://input')));

        $this->load->model('account/address');
        if($this->customer->isLogged()){
            $data['customerInfo'] = [];

            if(isset($param['address_id']) && $param['address_id'] != 0){
                $address_id = $param['address_id'];
            }else{
                $address_id = $this->customer->getAddressId();
            }

            $data['customerInfo']['login'] = $this->customer->isLogged() ? true : false;
            $data['customerInfo']['customer_id'] = $this->customer->getId();
            $data['customerInfo']['email'] = $this->customer->getEmail();
            $data['customerInfo']['first_name'] = $this->customer->getFirstName();
            $data['customerInfo']['last_name'] = $this->customer->getLastName();
            $data['customerInfo']['telephone'] = $this->customer->getTelephone();
            $data['customerInfo']['payment_address'] = $this->model_account_address->getAddress($address_id);
            $data['customerInfo']['payment_address']['type'] = 'payment';
            $data['customerInfo']['shipping_address'] = $this->model_account_address->getAddress($address_id);
            $data['customerInfo']['shipping_address']['type'] = 'shipping';
        }else{
            $data['warning'] = 'Üye girişi yapılmamış';
        }
        
        $this->printOutput($data);
    }

    public function login()
    {
        //https://www.deercase.com/index.php?route=checkout/odeme/login

        $param = array_merge($_POST, (array) json_decode(file_get_contents('php://input')));

        $data = [];
        $data['warning'] = null;

        $this->load->model('account/customer');
        $this->load->model('account/address');
        $this->load->language('account/login');


        if (isset($param['email']) AND isset($param['password'])) {

            $customer_info = $this->model_account_customer->getCustomerByEmail($param['email']);

            if ($customer_info && !$customer_info['approved']) {
                $data['warning'] = $this->language->get('error_approved');
            }

            if (!$data['warning']) {
                if (!$this->customer->login($param['email'], $param['password'])) {
                    $data['warning'] = $this->language->get('error_login');
                    $this->model_account_customer->addLoginAttempt($param['email']);
                } else {
                    $data['customerInfo'] = [];

                    $data['customerInfo']['login'] = $this->customer->isLogged() ? true : false;
                    $data['customerInfo']['customer_id'] = $this->customer->getId();
                    $data['customerInfo']['email'] = $this->customer->getEmail();
                    $data['customerInfo']['first_name'] = $this->customer->getFirstName();
                    $data['customerInfo']['last_name'] = $this->customer->getLastName();
                    $data['customerInfo']['telephone'] = $this->customer->getTelephone();
                    $data['customerInfo']['payment_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
                    $data['customerInfo']['payment_address']['type'] = 'payment';
                    $data['customerInfo']['shipping_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
                    $data['customerInfo']['shipping_address']['type'] = 'shipping';
                    $this->model_account_customer->deleteLoginAttempts($param['email']);
                }
            }

        }else{
            $data['error'] = 'Kullanıcı adı ve şifre gönderilmelidir!';
        }

        $this->printOutput($data);

    }

    public function logout()
    {
        $this->customer->logout();
    }

    public function register()
    {

        //https://www.deercase.com/index.php?route=checkout/odeme/register

        $param = array_merge($_POST, (array) json_decode(file_get_contents('php://input')));

        $this->load->model('account/customer');

        if(isset($param['firstname']) && isset($param['lastname']) && isset($param['email']) && isset($param['telephone']) && isset($param['password'])){

            if ($this->model_account_customer->getTotalCustomersByEmail($param['email'])) {
                $data['warning'] = 'Bu E-Posta adresi ile daha önce kayıt olunmuştur!';
            }else{
                $param['newsletter'] = 0;

                $param['telephone'] = str_replace(array('(',')','-',' '), array('','','',''), $param['telephone']);

                $data['customerInfo']['customer_id'] = $this->model_account_customer->addCustomer($param);
                $this->customer->login($param['email'], $param['password']);
                $data['customerInfo']['login'] = true;
                $data['customerInfo']['email'] = $param['email'];
                $data['customerInfo']['first_name'] = $param['firstname'];
                $data['customerInfo']['last_name'] = $param['lastname'];
                $data['customerInfo']['telephone'] = $param['telephone'];
                $data['success'] = true;

            }

        }else{
            $data['warning'] = 'Sorun oluştu';
        }

        $this->printOutput($data);

    }

    public function guest()
    {

        //https://www.deercase.com/index.php?route=checkout/odeme/guest

        $param = array_merge($_POST, (array) json_decode(file_get_contents('php://input')));

        $customer_group_id = $this->config->get('config_customer_group_id');

        $this->session->data['account'] = 'guest';

        $this->session->data['guest']['customer_group_id'] = $customer_group_id;
        $this->session->data['guest']['firstname'] = $param['firstname'];
        $this->session->data['guest']['lastname'] = $param['lastname'];
        $this->session->data['guest']['email'] = $param['email'];
        $this->session->data['guest']['telephone'] = $param['telephone'];
        $this->session->data['guest']['fax'] = '';

        $this->session->data['guest']['custom_field'] = array();

        $data['customerInfo'] = [];

        $data['customerInfo']['login'] = false;
        $data['customerInfo']['email'] = $param['email'];
        $data['customerInfo']['firstname'] = $param['firstname'];
        $data['customerInfo']['lastname'] = $param['lastname'];
        $data['customerInfo']['telephone'] = $param['telephone'];
        $data['customerInfo']['guest'] = true;

        

        $this->printOutput($data);


    }

    public function getCartProducts()
    {

        //https://www.deercase.com/index.php?route=checkout/odeme/getCartProducts

        $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']);
                $display_price = $this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax'));
            } else {
                $price = false;
                $display_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']);
                $display_total = $this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')) * $product['quantity'];
            } else {
                $total = false;
                $display_total = false;
            }

            $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,
                'quantity' => (int)$product['quantity'],
                'stock' => $product['stock'] ? true : !(!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning')),
                'price' => $display_price,
                'display_price' => $price,
                'total' => $display_total,
                'display_total' => $total,
            );
        }

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

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

        // Because __call can not keep var references so we put them into an array.
        $total_data = array(
            'totals' => &$totals,
            'taxes' => &$taxes,
            'total' => &$total
        );


        // Display prices
        if ($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']);
                    // We have to put the totals in an array so that they pass by reference.
                    $this->{'model_extension_total_' . $result['code']}->getTotal($total_data);
                }
            }

            $sort_order = array();

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


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

        //var_dump($totals); die();

        $data['totals'] = array();
        foreach ($totals as $total) {
            if($total['code'] != 'tax' && $total['code'] != 'shipping' && $total['code'] != 'campaign_price_total'){
                $data['totals'][] = array(
                    'title' => $total['title'],
                    'text' => $this->currency->format($total['value'], $this->session->data['currency'])
                );
            }

            if($total['code']=='total'){
                $data['total_amt'] = str_replace(',','.',str_replace('₺','',$this->currency->format($total['value'], $this->session->data['currency'])));
            }
        }

        $this->printOutput($data);

    }

    public function add() {


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

        $json = array();

        $param = array_merge($_POST, (array) json_decode(file_get_contents('php://input')));


        if (isset($param['product_id'])) {
            $product_id = (int) $param['product_id'];
        } else {
            $product_id = 0;
        }
        $p_11_pattern_img="";
        if (isset($param['p_11_pattern_img'])) {
            $p_11_pattern_img = $param['p_11_pattern_img'];
        }
        $returnError = false;
        if (isset($param['customizetext']) && mb_strlen($param['customizetext'])>15) {
            $returnError = true;
        }

        if (isset($param['gradienttext']) && mb_strlen($param['gradienttext'])>3) {
            $returnError = true;
        }

        if ($returnError) {
            header('HTTP/1.1 500 Validation Error X');
            header('Content-Type: application/json; charset=UTF-8');
            $json['error']['text_count'] = 'Lütfen 10 karakter giriniz!';
        }

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

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

        if ($product_info) {
            if (isset($param['quantity']) && ((int) $param['quantity'] >= $product_info['minimum'])) {
                $quantity = (int) $param['quantity'];
            } else {
                $quantity = $product_info['minimum'] ? $product_info['minimum'] : 1;
            }


            if (isset($param['option'])) {
                $option = array_filter($param['option']);
            } else {
                $option = array();
            }

            $product_options = $this->model_catalog_product->getProductOptions($param['product_id']);

            foreach ($product_options as $product_option) {
                if ($product_option['required'] && empty($option[$product_option['product_option_id']])) {
                    $json['error']['option'][$product_option['product_option_id']] = sprintf($this->language->get('error_required'), $product_option['name']);
                }
            }


            $pattern_data = $customer_order_image = $order_img = $customcaseimage = '';

            if (isset($param['order_img']) && $param['order_img'] != '') {
                $order_img = 'pattern_resize/' . $param['order_img'];
            }

            if (isset($param['customizetext'])) {

                if ($product_info['product_type'] == 4 || $product_info['product_type'] == 8)
                    $text_position = 'Center';
                else
                    $text_position = 'Bottom';
                $font = 'Glitter';
                $font_color = '000000';
                $texture = '1.jpg';
                $gradienttext = '';
                $text = '';
                $is_circle = '';
                if ($param['customizetext'] != '') {
                    $text = trim($param['customizetext']);
                    $text_count = mb_strlen($text, 'UTF-8');
                    if ($text_count > 15) {
                        $json['error']['text_count'] = 'Lütfen 10 karakter giriniz!';
                    }
                }
                if ($param['customizeFont'] != null) {
                    $font = $param['customizeFont'];
                }
                if ($param['customizeColor'] != null) {
                    $font_color = $param['customizeColor'];
                }
                if ($param['customizetextPosition'] != null) {
                    $text_position = $param['customizetextPosition'];
                }

                if (isset($param['texture'])) {
                    $texture = $param['texture'];
                }
                if (isset($param['product_type'])) {
                    $product_type = $param['product_type'];
                }
                if (isset($param['gradienttext']) && trim($param['gradienttext']) != '') {
                    $gradienttext = $param['gradienttext'];
                }
                $text2 = '';
                if (isset($param['customizetext2'])) {
                    $text2 = trim($param['customizetext2']);
                    $text_count = mb_strlen($text2, 'UTF-8');
                    if ($text_count > 15) {
                        $json['error']['text_count'] = 'Lütfen 10 karakter giriniz!';
                    }
                }

                $pattern_data = json_encode(array('pattern_text' => htmlspecialchars_decode($text), 'font' => $font, 'font_color' => $font_color, 'text_pos' => $text_position, 'pattern_text2' => htmlspecialchars_decode($text2), 'gradienttext' => htmlspecialchars_decode($gradienttext), 'texture' => $texture, 'product_type' => $product_type), JSON_UNESCAPED_UNICODE);
            }

            if (isset($param['customcaseimage'])) {
                $customcaseimage = $param['customcaseimage'];
                $customcaseimage = $product_info['href'] . '***' . $customcaseimage;
            }

            if (!$json) {
                $cart_id = $this->cart->add($param['product_id'], $quantity, $option, 0, $order_img, $customer_order_image, $pattern_data, $customcaseimage,$p_11_pattern_img);

                $json['success'] = sprintf($this->language->get('text_success'), $this->url->link('product/product', 'product_id=' . $param['product_id']), $product_info['name'], $this->url->link('checkout/cart'));
                $json['cart_id'] = $cart_id;
                // Unset all shipping and payment methods
                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('extension/extension');

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

                // Because __call can not keep var references so we put them into an array.
                $total_data = array(
                    'totals' => &$totals,
                    'taxes' => &$taxes,
                    'total' => &$total
                );

                // Display prices
                if ($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']);

                            // We have to put the totals in an array so that they pass by reference.
                            $this->{'model_extension_total_' . $result['code']}->getTotal($total_data);
                        }
                    }

                    $sort_order = array();

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

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


                $json['total'] = sprintf($this->language->get('text_items'), $this->cart->countProducts() + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0), $this->currency->format($total, $this->session->data['currency']));
                $json['itemstotal'] = $this->cart->countProducts();
                $json['text_items_only'] = $this->cart->countProducts();

                $json['text_price_only'] = $this->currency->format($total, $this->session->data['currency']);
            } else {
                $json['redirect'] = str_replace('&amp;', '&', $this->url->link('product/product', 'product_id=' . $this->request->post['product_id']));
                if (isset($this->request->post['click']) || isset($this->request->post['ad_click'])) {
                    return $json;
                }
            }
        }

        $this->printOutput($json);
        
    }

    public function deleteCartItem()
    {
        //https://www.deercase.com/index.php?route=checkout/odeme/deleteCartItem

        $data = [];
        $param = array_merge($_POST, (array) json_decode(file_get_contents('php://input')));

        if(isset($param['key'])){
            $remove_options = $this->db->query("SELECT * FROM ps_cart WHERE cart_id = '" . $param['key'] . "' AND session_id = '" . $this->db->escape($this->session->getId()) . "' ");
            $remove_options = json_decode($remove_options->rows [0]['option']);

            foreach ($remove_options as $r_option)
                $this->cart->remove($r_option);

            $this->cart->remove($param['key']);

            $data['success'] = 'Ürün septetten silindi';
    
        }

        $this->printOutput($data);
    }

    public function editCartItem()
    {

        die();
        //https://www.deercase.com/index.php?route=checkout/odeme/editCartItem
        $data = [];
        $param = array_merge($_POST, (array) json_decode(file_get_contents('php://input')));

        if (!isset($param['quantity']))
            return false;

        // Update
        if (!empty($param['quantity'])) {
            foreach ($this->request->post['quantity'] as $key => $value) {
                $this->cart->update($key, $value);
            }

            $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->response->redirect($this->url->link('checkout/cart'));
        }

    }

    public function validateCoupon() {

        $param = array_merge($_POST, (array) json_decode(file_get_contents('php://input')));

        $this->load->language('checkout/checkout');
        $this->load->language('quickcheckout/checkout');

        $json = array();

        if (!isset($param['coupon']) || empty($param['coupon'])) {
            $param['coupon'] = '';
            $this->session->data['coupon'] = '';
        }

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

        if ($param['coupon'] == '') {
            unset($this->session->data['coupon']);

            $json['success'] = $this->language->get('text_coupon_removed');
        } else {
            $coupon_info = $this->model_extension_total_coupon->getCoupon($param['coupon']);

            /**
             * 01.09.20 return coupon cannot be used width any promotions (ali a.)
             */
            if (!$coupon_info) {
                $json['error']['warning'] = $this->language->get('error_coupon');
            }else if($this->config->get('promotion')['4al2ode']){
                $expo = explode('-', $param['coupon']);
                if(!isset($expo[1]) AND $this->cart->countProducts() >= 4){
                    if (isset($this->session->data['coupon'])) {
                        unset($this->session->data['coupon']);
                    }
                    $json['error']['warning'] = $this->language->get('error_campaign_coupon');
                }
            }
            else if (isset($this->session->data['campaign_price_total']) && $coupon_info['return_coupon'] == 1) {

                if (isset($this->session->data['coupon'])) {
                    unset($this->session->data['coupon']);
                }

                $json['error']['warning'] = $this->language->get('error_return_coupon');
            }
            /**
             * end of update (ali a.)
             */

            if (!$json) {
                $this->session->data['coupon'] = $param['coupon'];

                $json['success'] = $this->language->get('text_coupon');
            }
        }

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

    public function getCustomerAdresses()
    {
        //https://www.deercase.com/index.php?route=checkout/odeme/getCustomerAdresses
        $this->load->model('account/address');

        $json['addresses'] = [];
        foreach ($this->model_account_address->getAddresses() as $address){
            $json['addresses'][] = $address;
        }

        $this->printOutput($json);

    }

    public function shippingMethods() {

        //https://www.deercase.com/index.php?route=checkout/odeme/shippingMethods

        $param = array_merge($_POST, (array) json_decode(file_get_contents('php://input')));

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

        $shipping_address = array();

        if ($this->customer->isLogged() && isset($param['address_id'])) {
            // Selected stored address
            $shipping_address = $this->model_account_address->getAddress($param['address_id']);

            if (isset($this->session->data['guest'])) {
                unset($this->session->data['guest']);
            }
        } elseif (isset($param['country_id'])) {
            // Selected new address OR is a guest
            if (isset($param['country_id'])) {
                $country_info = $this->model_localisation_country->getCountry($param['country_id']);
            } else {
                $country_info = '';
            }

            if (isset($param['zone_id'])) {
                $zone_info = $this->model_localisation_zone->getZone($param['zone_id']);
            } else {
                $zone_info = '';
            }

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

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

            $shipping_address['firstname'] = $param['firstname'];
            $shipping_address['lastname'] = $param['lastname'];
            $shipping_address['address_1'] = $param['address_1'];
            $shipping_address['address_2'] = $param['address_2'];
            $shipping_address['postcode'] = $param['postcode'];
            $shipping_address['city'] = isset($param['city']) ? $param['city'] : '';
            $shipping_address['country_id'] = $param['country_id'];
            $shipping_address['zone_id'] = $param['zone_id'];
        }

        if (!empty($shipping_address)) {
            // Shipping Methods
            $method_data = array();

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

            $results = $this->model_extension_extension->getExtensions('shipping');

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

                    $quote = $this->{'model_extension_shipping_' . $result['code']}->getQuote($shipping_address);

                    if ($quote) {
                        $method_data[$result['code']] = array(
                            'title'      => $quote['title'],
                            'quote'      => $quote['quote'],
                            'sort_order' => $quote['sort_order'],
                            'error'      => $quote['error'],
                            'code'       => $result['code']
                        );
                    }


                }
            }

            $sort_order = array();

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

            array_multisort($sort_order, SORT_ASC, $method_data);

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


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

        if (isset($this->session->data['shipping_methods'])) {
            $data['shipping_methods'] = $this->session->data['shipping_methods'];
        } else {
            $data['shipping_methods'] = array();
        }

        if (isset($this->session->data['shipping_method']['code'])) {
            $data['code'] = $this->session->data['shipping_method']['code'];
        } else {
            $data['code'] = $this->config->get('quickcheckout_shipping_default');
        }

        $exists = false;
        $stored_code = false;

        foreach ($data['shipping_methods'] as $key => $shipping_method) {
            if ($key == $data['code']) {
                foreach ($shipping_method['quote'] as $quote) {
                    $exists = true;
                    $data['code'] = $quote['code'];
                    break;
                }

                break;
            } else {
                foreach ($shipping_method['quote'] as $quote) {
                    if (!$stored_code) {
                        $stored_code = $quote['code'];
                    }
                    if ($quote['code'] == $data['code']) {
                        $exists = true;
                        break;
                    }
                }
            }
        }

        if (!$exists) {
            $data['code'] = $stored_code;
        }



        $this->printOutput($data);

    }

    private function setShippingMethod($param) {

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

        if ($this->customer->isLogged() && isset($param['address_id'])) {
            // Selected stored address
            $this->session->data['shipping_address_id'] = $param['address_id'];

            $this->session->data['shipping_address'] = $this->model_account_address->getAddress($param['address_id']);

            if (isset($this->session->data['guest'])) {
                unset($this->session->data['guest']);
            }
        } elseif (isset($param['country_id'])) {
            // Selected new address OR is a guest
            if (isset($param['country_id'])) {
                $country_info = $this->model_localisation_country->getCountry($param['country_id']);
            } else {
                $country_info = '';
            }

            if (isset($param['zone_id'])) {
                $zone_info = $this->model_localisation_zone->getZone($param['zone_id']);
            } else {
                $zone_info = '';
            }

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

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

            $shipping_address['firstname'] = $param['firstname'];
            $shipping_address['lastname'] = $param['lastname'];
            $shipping_address['company'] = $param['company'];
            $shipping_address['address_1'] = $param['address_1'];
            $shipping_address['address_2'] = $param['address_2'];
            $shipping_address['postcode'] = $param['postcode'];
            $shipping_address['city'] = $param['city'];
            $shipping_address['country_id'] = $param['country_id'];
            $shipping_address['zone_id'] = $param['zone_id'];
            $shipping_address['custom_field'] = [];

            $this->session->data['shipping_address'] = $shipping_address;
        }

        if (isset($param['delivery_date'])) {
            $this->session->data['delivery_date'] = strip_tags($this->request->post['delivery_date']);
        }

        if (isset($param['delivery_time'])) {
            $this->session->data['delivery_time'] = strip_tags($this->request->post['delivery_time']);
        }

        if (isset($param['shipping_method']) && isset($this->session->data['shipping_methods'])) {
            $shipping = explode('.', $param['shipping_method']);

            if (isset($this->session->data['shipping_methods'][$shipping[0]]['quote'][$shipping[1]])) {
                $this->session->data['shipping_method'] = $this->session->data['shipping_methods'][$shipping[0]]['quote'][$shipping[1]];
            }
        }

    }

    public function paymentMethods() {

        //https://www.deercase.com/index.php?route=checkout/odeme/paymentMethods

        $param = array_merge($_POST, (array) json_decode(file_get_contents('php://input')));


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

        $payment_address = array();


        if ($this->customer->isLogged() && isset($param['address_id'])) {
            // Selected stored address
            $payment_address = $this->model_account_address->getAddress($param['address_id']);
            if (isset($this->session->data['guest'])) {
                unset($this->session->data['guest']);
            }
        } elseif (isset($param['country_id'])) {

            // Selected new address OR is a guest
            if (isset($param['country_id'])) {
                $country_info = $this->model_localisation_country->getCountry($param['country_id']);
            } else {
                $country_info = '';
            }

            if (isset($param['zone_id'])) {
                $zone_info = $this->model_localisation_zone->getZone($param['zone_id']);
            } else {
                $zone_info = '';
            }

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

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


            $payment_address['firstname'] = $param['firstname'];
            $payment_address['lastname'] = $param['lastname'];
            $payment_address['company'] = $param['company'];
            $payment_address['address_1'] = $param['address_1'];
            $payment_address['address_2'] = $param['address_2'];
            $payment_address['postcode'] = '';
            $payment_address['city'] = isset($param['city']) ? $param['city'] : '';
            $payment_address['country_id'] = $param['country_id'];
            $payment_address['zone_id'] = $param['zone_id'];
        }

        if (!empty($payment_address)) {
            // Totals
            $total_data = array();
            $total = 0;
            $taxes = $this->cart->getTaxes();

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

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

            $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);
                }
            }

            // Payment Methods
            $method_data = array();

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

            $results = $this->model_extension_extension->getExtensions('payment');

            $recurring = $this->cart->hasRecurringProducts();

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

                    $method = $this->{'model_extension_payment_' . $result['code']}->getMethod($payment_address, $total);

                    if ($method) {
                        if ($recurring) {
                            if (property_exists($this->{'model_extension_payment_' . $result['code']}, 'recurringPayments') && $this->{'model_extension_payment_' . $result['code']}->recurringPayments()) {
                                $method_data[$result['code']] = $method;
                            }
                        } else {
                            $method_data[$result['code']] = $method;
                        }
                    }
                }
            }

            $sort_order = array();

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

            array_multisort($sort_order, SORT_ASC, $method_data);

            $this->session->data['payment_methods'] = $method_data;
        }


        if (empty($this->session->data['payment_methods'])) {
            $data['error_warning'] = sprintf($this->language->get('error_no_payment'), $this->url->link('information/contact'));
        } else {
            $data['error_warning'] = '';
        }

        if (isset($this->session->data['payment_methods'])) {
            $data['payment_methods'] = $this->session->data['payment_methods'];
        } else {
            $data['payment_methods'] = array();
        }

        if (isset($this->session->data['payment_method']['code'])) {
            $data['code'] = $this->session->data['payment_method']['code'];
        } else {
            $data['code'] = $this->config->get('quickcheckout_payment_default');
        }

        $exists = false;
        $stored_code = false;

        foreach ($data['payment_methods'] as $payment_method) {
            if (!$stored_code) {
                $stored_code = $payment_method['code'];
            }

            if ($payment_method['code'] == $data['code']) {
                $exists = true;

                break;
            }
        }

        if (!$exists) {
            $data['code'] = $stored_code;
        }

        if (isset($param['comment'])) {
            $data['comment'] = $this->request->post['comment'];
        } elseif (isset($this->session->data['order_comment'])) {
            $data['comment'] = $this->session->data['order_comment'];
        } else {
            $data['comment'] = '';
        }

        $methods = array();
        foreach ($data['payment_methods'] as $key => $method){
            $methods[] = array(
                'code' => $key,
                'title' => $data['payment_methods'][$key]['title'],
            );
        }


        $data['payment_methods'] = $methods;


        $this->printOutput($data);

    }

    private function setPaymentMethod($param) {


        $this->load->model('account/address');
		$this->load->model('localisation/country');
		$this->load->model('localisation/zone');
		
		if ($this->customer->isLogged() && isset($param['address_id'])) {
			// Selected stored address
			$this->session->data['payment_address_id'] = $param['address_id'];
						
			$this->session->data['payment_address'] = $this->model_account_address->getAddress($param['address_id']);
			
			if (isset($this->session->data['guest'])) {
				unset($this->session->data['guest']);
			}
		} elseif (isset($param['country_id'])) {
			// Selected new address OR is a guest
			if (isset($param['country_id'])) {
				$country_info = $this->model_localisation_country->getCountry($param['country_id']);
			} else {
				$country_info = '';
			}
			
			if (isset($param['zone_id'])) {
				$zone_info = $this->model_localisation_zone->getZone($param['zone_id']);
			} else {
				$zone_info = '';
			}
			
			if ($country_info) {
				$payment_address['country'] = $country_info['name'];
				$payment_address['iso_code_2'] = $country_info['iso_code_2'];
				$payment_address['iso_code_3'] = $country_info['iso_code_3'];
				$payment_address['address_format'] = $country_info['address_format'];
			} else {
				$payment_address['country'] = '';
				$payment_address['iso_code_2'] = '';
				$payment_address['iso_code_3'] = '';
				$payment_address['address_format'] = '';
			}
			
			if ($zone_info) {
				$payment_address['zone'] = $zone_info['name'];
				$payment_address['zone_code'] = $zone_info['code'];
			} else {
				$payment_address['zone'] = '';
				$payment_address['zone_code'] = '';
			}
		
			$payment_address['firstname'] = $param['firstname'];
			$payment_address['lastname'] = $param['lastname'];
			$payment_address['company'] = $param['company'];
			$payment_address['company_taxno'] = $param['company_taxno'];
			$payment_address['company_taxadmin'] = $param['company_taxadmin'];
			$payment_address['address_1'] = $param['address_1'];
			$payment_address['address_2'] = $param['address_2'];
			$payment_address['postcode'] = $param['postcode'];
			$payment_address['city'] = isset($param['city']) ? $param['city'] : '';
			$payment_address['country_id'] = $param['country_id'];
			$payment_address['zone_id'] = $param['zone_id'];
			$payment_address['custom_field'] = array();
			
			$this->session->data['payment_address'] = $payment_address;
            if(!isset($this->session->data['guest'])){
                $this->session->data['guest'] = $payment_address;
            }
			 
		}
		
		if (isset($param['survey'])) {
			$this->session->data['survey'] = strip_tags($this->request->post['survey']);
		}
		
		if (isset($param['comment'])) {
			$this->session->data['order_comment'] = strip_tags($this->request->post['comment']);
		}

		if (isset($param['payment_method']) && isset($this->session->data['payment_methods'][$param['payment_method']])) {
			$this->session->data['payment_method'] = $this->session->data['payment_methods'][$param['payment_method']];
		}

        //$this->printOutput($json);
    }

    public function setGuestAddress()
    {
        $data = [];
        $param = array_merge($_POST, (array) json_decode(file_get_contents('php://input')));

       // var_dump((array)$param); die();

        $payment_address = (array)$param['address_data']->payment_address;
        $shipping_address = (array)$param['address_data']->shipping_address;
        $customer = (array)$param['customer'];


            $this->session->data['account'] = 'guest';

            $this->session->data['guest']['customer_group_id'] = $this->config->get('config_customer_group_id');
            $this->session->data['guest']['firstname'] = $customer['firstname'];
            $this->session->data['guest']['lastname'] = $customer['lastname'];
            $this->session->data['guest']['email'] = $customer['email'];
            $this->session->data['guest']['telephone'] = $customer['telephone'];
            $this->session->data['guest']['fax'] = '';

            
            $this->session->data['guest']['custom_field'] = array();
            

            $this->session->data['payment_address']['firstname'] = $payment_address['firstname'];
            $this->session->data['payment_address']['lastname'] = $payment_address['lastname'];
            $this->session->data['payment_address']['address_1'] = $payment_address['address_1'];
            $this->session->data['payment_address']['address_2'] = '';
            $this->session->data['payment_address']['postcode'] = '';
            $this->session->data['payment_address']['city'] = $payment_address['city'];
            $this->session->data['payment_address']['country_id'] = $payment_address['country_id'];
            $this->session->data['payment_address']['zone_id'] = $payment_address['zone_id'];
            $this->session->data['payment_address']['company'] = $payment_address['company'];
            $this->session->data['payment_address']['company_taxno'] = isset($payment_address['company_taxno']) ? $payment_address['company_taxno'] : '';
            $this->session->data['payment_address']['company_taxadmin'] = isset($payment_address['company_taxadmin']) ? $payment_address['company_taxadmin'] : '';


            $this->session->data['payment_address']['type'] = 'payment';
            $this->session->data['payment_address']['guest'] = true;


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

            $country_info = $this->model_localisation_country->getCountry($payment_address['country_id']);

            if ($country_info) {
                $this->session->data['payment_address']['country'] = $country_info['name'];
                $this->session->data['payment_address']['iso_code_2'] = $country_info['iso_code_2'];
                $this->session->data['payment_address']['iso_code_3'] = $country_info['iso_code_3'];
                $this->session->data['payment_address']['address_format'] = $country_info['address_format'];
            } else {
                $this->session->data['payment_address']['country'] = '';
                $this->session->data['payment_address']['iso_code_2'] = '';
                $this->session->data['payment_address']['iso_code_3'] = '';
                $this->session->data['payment_address']['address_format'] = '';
            }


            $this->session->data['payment_address']['custom_field'] = array();


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

            $zone_info = $this->model_localisation_zone->getZone($payment_address['zone_id']);

            if ($zone_info) {
                $this->session->data['payment_address']['zone'] = $zone_info['name'];
                $this->session->data['payment_address']['zone_code'] = $zone_info['code'];
            } else {
                $this->session->data['payment_address']['zone'] = '';
                $this->session->data['payment_address']['zone_code'] = '';
            }

            $city_info = $this->model_localisation_zone->getCity($payment_address['city_id']);

            if ($city_info) {
                $this->session->data['payment_address']['city'] = $city_info['district_name'];
                $this->session->data['payment_address']['city_id'] = $city_info['district_id'];
            } else {
                $this->session->data['payment_address']['city'] = '';
                $this->session->data['payment_address']['city_id'] = '';
            }

            if (!empty($shipping_address)) {
                $this->session->data['guest']['shipping_address'] = $shipping_address;
            } else {
                $this->session->data['guest']['shipping_address'] = false;
            }

            // Default Payment Address
            if ($this->session->data['guest']['shipping_address']) {
                $this->session->data['shipping_address']['firstname'] = $shipping_address['firstname'];
                $this->session->data['shipping_address']['lastname'] = $shipping_address['lastname'];
                $this->session->data['shipping_address']['company'] = '';
                $this->session->data['shipping_address']['address_1'] = $shipping_address['address_1'];
                $this->session->data['shipping_address']['address_2'] = '';
                $this->session->data['shipping_address']['postcode'] = '';
                $this->session->data['shipping_address']['city'] = $shipping_address['city'];
                $this->session->data['shipping_address']['country_id'] = $shipping_address['country_id'];
                $this->session->data['shipping_address']['zone_id'] = $shipping_address['zone_id'];

                $country_info = $this->model_localisation_country->getCountry($shipping_address['country_id']);

                if ($country_info) {
                    $this->session->data['shipping_address']['country'] = $country_info['name'];
                    $this->session->data['shipping_address']['iso_code_2'] = $country_info['iso_code_2'];
                    $this->session->data['shipping_address']['iso_code_3'] = $country_info['iso_code_3'];
                    $this->session->data['shipping_address']['address_format'] = $country_info['address_format'];
                } else {
                    $this->session->data['shipping_address']['country'] = '';
                    $this->session->data['shipping_address']['iso_code_2'] = '';
                    $this->session->data['shipping_address']['iso_code_3'] = '';
                    $this->session->data['shipping_address']['address_format'] = '';
                }

                $zone_info = $this->model_localisation_zone->getZone($shipping_address['zone_id']);

                if ($zone_info) {
                    $this->session->data['shipping_address']['zone'] = $zone_info['name'];
                    $this->session->data['shipping_address']['zone_code'] = $zone_info['code'];
                } else {
                    $this->session->data['shipping_address']['zone'] = '';
                    $this->session->data['shipping_address']['zone_code'] = '';
                }

                $city_info = $this->model_localisation_zone->getCity($shipping_address['city_id']);

                if ($city_info) {
                    $this->session->data['shipping_address']['city'] = $city_info['district_name'];
                    $this->session->data['shipping_address']['city_id'] = $city_info['district_id'];
                } else {
                    $this->session->data['shipping_address']['city'] = '';
                    $this->session->data['shipping_address']['city_id'] = '';
                }

                $this->session->data['shipping_address']['custom_field'] = array();
                $this->session->data['shipping_address']['type'] = 'shipping';

            }



        $data['payment_address'] = $this->session->data['payment_address'];
        $data['shipping_address'] = $this->session->data['shipping_address'];
        $data['customer'] = $this->session->data['guest'];


        $this->printOutput($data);
    }

    public function saveCustomerAddress()
    {

        $data = [];
        $param = array_merge($_POST, (array) json_decode(file_get_contents('php://input')));

        //var_dump((array)$param); die();

        $this->load->model('account/address');

        $data['address_id'] = 0;

        if($param['addresses_same'] && $param['payment_address']->address_id == 0){
            $data['address_id'] = $this->model_account_address->addAddress((array)$param['payment_address']);
        }elseif(!$param['addresses_same'] && $param['payment_address']->address_id != $param['shipping_address']->address_id){
            $data['address_id'] = $this->model_account_address->editAddress($param['payment_address']->address_id,(array)$param['payment_address']);
            $this->model_account_address->editAddress($param['shipping_address']->address_id,(array)$param['shipping_address']);
        }elseif(!$param['addresses_same'] && $param['payment_address']->address_id == $param['shipping_address']->address_id){
            $data['address_id'] = $this->model_account_address->editAddress($param['payment_address']->address_id,(array)$param['payment_address']);
        }

        $this->printOutput($data);
        
    }

    public function terms()
    {

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

        if ($this->config->get('config_checkout_id')) {
            $this->load->model('catalog/information');

            $information_info = $this->model_catalog_information->getInformation($this->config->get('config_checkout_id'));

            if ($information_info) {
                $data['text_agree'] = sprintf($this->language->get('text_agree'), $this->url->link('information/information/agree', 'information_id=' . $this->config->get('config_checkout_id'), true), $information_info['title'], $information_info['title']);
            } else {
                $data['text_agree'] = '';
            }
        } else {
            $data['text_agree'] = '';
        }

        if ($this->config->get('config_checkout_id2')) {
            $this->load->model('catalog/information');

            $information_info = $this->model_catalog_information->getInformation($this->config->get('config_checkout_id2'));

            if ($information_info) {
                $data['text_agree2'] = sprintf($this->language->get('text_agree'), $this->url->link('information/information/agree', 'information_id=' . $this->config->get('config_checkout_id2'), true), $information_info['title'], $information_info['title']);
            } else {
                $data['text_agree2'] = '';
            }
        } else {
            $data['text_agree2'] = '';
        }

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

        $proceed_button_text = $this->config->get('quickcheckout_proceed_button_text');

        if (!empty($proceed_button_text[$this->config->get('config_language_id')])) {
            $data['button_continue'] = $proceed_button_text[$this->config->get('config_language_id')];
        }

        $this->printOutput($data);


    }

    public function voucer()
    {

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

        $points_total = 0;

        foreach ($this->cart->getProducts() as $product) {
            if ($product['points']) {
                $points_total += $product['points'];
            }
        }

        $data['entry_reward'] = sprintf($this->language->get('entry_reward'), $points_total, $this->customer->getRewardPoints());

        if ($points_total && $this->customer->isLogged()) {
            $data['reward'] = true;
        } else {
            $data['reward'] = false;
        }

        // All variables
        $data['voucher_module'] = $this->config->get('quickcheckout_voucher');
        $data['coupon_module'] = $this->config->get('quickcheckout_coupon');
        $data['reward_module'] = $this->config->get('quickcheckout_reward');

        $this->printOutput($data);

    }

    public function countries()
    {
        //https://www.deercase.com/index.php?route=checkout/odeme/countries

        $json = [];
        $this->load->model('localisation/country');

        $countries = $this->model_localisation_country->getCountries();
        $this->printOutput($countries);

    }

    public function zones()
    {
        //https://www.deercase.com/index.php?route=checkout/odeme/zones

        $json = [];
        $param = array_merge($_POST, (array) json_decode(file_get_contents('php://input')));

        if(isset($param['country_id'])){
            $param['country_id'] = $param['country_id'];
        }else{
            $param['country_id'] = 215;
        }

        $this->load->model('localisation/zone');
            $zones = $this->model_localisation_zone->getZonesByCountryId($param['country_id']);

            foreach ($zones as $key => $zone){
                $cities = $this->model_localisation_zone->getCities($zone['zone_id']);
                $json[] = array(
                    'info' => $zone,
                    'cities' => $cities
                );
                
            }
        $this->printOutput($json);

    }

    public function localisation()
    {
        //https://www.deercase.com/index.php?route=checkout/odeme/localisation

        if($this->cache->cache_get($this->session->data['language'] . '_all_country', 'cauntries/')){
            return $this->cache->cache_get($this->session->data['language'] . '_all_country', 'cauntries/');
        }
            

        $json = [];
        $this->load->model('localisation/country');
        $this->load->model('localisation/zone');

        $countries = $this->model_localisation_country->getCountries();

        foreach($countries as $country){
            // $zones = $this->model_localisation_zone->getZonesByCountryId($country['country_id']);
            foreach ($zones as $key => $zone){
                $cities = $this->model_localisation_zone->getCities($zone['zone_id']);
                $zones[$key]['cities'] = $cities;
            }

            $json['countries'][$country['country_id']] = array(
                'country_id'        => $country['country_id'],
                'name'              => $country['name'],
                'iso_code_2'        => $country['iso_code_2'],
                'iso_code_3'        => $country['iso_code_3'],
                'address_format'    => $country['address_format'],
                'postcode_required' => $country['postcode_required'],
                'status'            => $country['status'],
                'zones'             => [],
            );
        }

        $this->cache->cache_set($this->session->data['language'] . '_all_country', $json['countries'], 'cauntries/');
        

        $this->printOutput($json);

    }

    public function setConfirm(){

        $param = array_merge($_POST, (array) json_decode(file_get_contents('php://input')));


        $this->setShippingMethod($param);
        $this->setPaymentMethod($param);

        //var_dump($this->session->data['guest']); die();

        $redirect = '';

        if ($this->cart->hasShipping()) {
            // Validate if shipping address has been set.
            if (!isset($this->session->data['shipping_address'])) {
                $redirect = 'Shipping Address Not Found!';
            }

            // Validate if shipping method has been set.
            if (!isset($this->session->data['shipping_method'])) {
                $redirect = 'Shipping Method Not Found!';
            }
        } else {
            unset($this->session->data['shipping_address']);
            unset($this->session->data['shipping_method']);
            unset($this->session->data['shipping_methods']);
        }

        // Validate if payment address has been set.
        if (!isset($this->session->data['payment_address'])) {
            $redirect = 'Payment Address Not Found!';
        }

        // Validate if payment method has been set.
        if (!isset($this->session->data['payment_method'])) {
            $redirect = 'Payment Method Not Found!';
        }

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

        // Validate minimum quantity requirements.
        $products = $this->cart->getProducts();

        $test_products0 = $products;

        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) {
                $redirect = $this->url->link('checkout/cart');

                break;
            }
        }

        if (!$redirect) {

            $order_data = array();

            $order_data['totals'] = array();
            $total = 0;
            $taxes = $this->cart->getTaxes();

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

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

            $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);
                }
            }

            $order_data['totals'] = $totals;

            $sort_order = array();

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

            array_multisort($sort_order, SORT_ASC, $order_data['totals']);

            
            $order_data['invoice_prefix'] = $this->config->get('config_invoice_prefix');
            $order_data['store_id'] = $this->config->get('config_store_id');
            $order_data['store_name'] = $this->config->get('config_name');

            if ($order_data['store_id']) {
                $order_data['store_url'] = $this->config->get('config_url');
            } else {
                $order_data['store_url'] = HTTP_SERVER;
            }

            if ($this->customer->isLogged()) {
                $this->load->model('account/customer');

                $customer_info = $this->model_account_customer->getCustomer($this->customer->getId());

                $order_data['customer_id'] = $this->customer->getId();
                $order_data['customer_group_id'] = $customer_info['customer_group_id'];
                $order_data['firstname'] = $customer_info['firstname'];
                $order_data['lastname'] = $customer_info['lastname'];
                $order_data['email'] = $customer_info['email'];
                $order_data['telephone'] = $customer_info['telephone'];
                $order_data['fax'] = $customer_info['fax'];
                $order_data['custom_field'] = json_decode($customer_info['custom_field']);
            } elseif (isset($this->session->data['guest'])) {
                $order_data['customer_id'] = 0;
                $order_data['customer_group_id'] = $this->session->data['guest']['customer_group_id'];
                $order_data['firstname'] = $this->session->data['guest']['firstname'];
                $order_data['lastname'] = $this->session->data['guest']['lastname'];
                $order_data['email'] = $this->session->data['guest']['email'];
                $order_data['telephone'] = $this->session->data['guest']['telephone'];
                $order_data['fax'] = $this->session->data['guest']['fax'];
                $order_data['custom_field'] = $this->session->data['guest']['custom_field'];
            }

            $order_data['payment_firstname'] = $this->session->data['payment_address']['firstname'];
            $order_data['payment_lastname'] = $this->session->data['payment_address']['lastname'];
            $order_data['payment_company'] = $this->session->data['payment_address']['company'];
            $order_data['payment_company_taxno'] = $this->session->data['payment_address']['company_taxno'];
            $order_data['payment_company_taxadmin'] = $this->session->data['payment_address']['company_taxadmin'];

            $order_data['payment_address_1'] = $this->session->data['payment_address']['address_1'];
            $order_data['payment_address_2'] = $this->session->data['payment_address']['address_2'];
            $order_data['payment_city'] = $this->session->data['payment_address']['city'];
            $order_data['payment_postcode'] = $this->session->data['payment_address']['postcode'];
            $order_data['payment_zone'] = $this->session->data['payment_address']['zone'];
            $order_data['payment_zone_id'] = $this->session->data['payment_address']['zone_id'];
            $order_data['payment_country'] = $this->session->data['payment_address']['country'];
            $order_data['payment_country_id'] = $this->session->data['payment_address']['country_id'];
            $order_data['payment_address_format'] = $this->session->data['payment_address']['address_format'];
            $order_data['payment_custom_field'] = $this->session->data['payment_address']['custom_field'];


            if (isset($this->session->data['payment_method']['title'])) {
                $order_data['payment_method'] = $this->session->data['payment_method']['title'];
            } else {
                $order_data['payment_method'] = '';
            }

            if (isset($this->session->data['payment_method']['code'])) {
                $order_data['payment_code'] = $this->session->data['payment_method']['code'];
            } else {
                $order_data['payment_code'] = '';
            }

            if ($this->cart->hasShipping()) {
                $order_data['shipping_firstname'] = $this->session->data['shipping_address']['firstname'];
                $order_data['shipping_lastname'] = $this->session->data['shipping_address']['lastname'];
                $order_data['shipping_company'] = '';
                $order_data['shipping_address_1'] = $this->session->data['shipping_address']['address_1'];
                $order_data['shipping_address_2'] = $this->session->data['shipping_address']['address_2'];
                $order_data['shipping_city'] = $this->session->data['shipping_address']['city'];
                $order_data['shipping_postcode'] = $this->session->data['shipping_address']['postcode'];
                $order_data['shipping_zone'] = $this->session->data['shipping_address']['zone'];
                $order_data['shipping_zone_id'] = $this->session->data['shipping_address']['zone_id'];
                $order_data['shipping_country'] = $this->session->data['shipping_address']['country'];
                $order_data['shipping_country_id'] = $this->session->data['shipping_address']['country_id'];
                $order_data['shipping_address_format'] = $this->session->data['shipping_address']['address_format'];
                $order_data['shipping_custom_field'] = $this->session->data['shipping_address']['custom_field'];

                if (isset($this->session->data['shipping_method']['title'])) {
                    $order_data['shipping_method'] = $this->session->data['shipping_method']['title'];
                } else {
                    $order_data['shipping_method'] = '';
                }

                if (isset($this->session->data['shipping_method']['code'])) {
                    $order_data['shipping_code'] = $this->session->data['shipping_method']['code'];
                } else {
                    $order_data['shipping_code'] = '';
                }
            } else {
                $order_data['shipping_firstname'] = '';
                $order_data['shipping_lastname'] = '';
                $order_data['shipping_company'] = '';
                $order_data['shipping_address_1'] = '';
                $order_data['shipping_address_2'] = '';
                $order_data['shipping_city'] = '';
                $order_data['shipping_postcode'] = '';
                $order_data['shipping_zone'] = '';
                $order_data['shipping_zone_id'] = '';
                $order_data['shipping_country'] = '';
                $order_data['shipping_country_id'] = '';
                $order_data['shipping_address_format'] = '';
                $order_data['shipping_custom_field'] = array();
                $order_data['shipping_method'] = '';
                $order_data['shipping_code'] = '';
            }

            $order_data['products'] = array();

            foreach ($this->cart->getProducts() as $product) {
                $option_data = array();

                foreach ($product['option'] as $option) {
                    $option_data[] = array(
                        'product_option_id' => $option['product_option_id'],
                        'product_option_value_id' => $option['product_option_value_id'],
                        'option_id' => $option['option_id'],
                        'option_value_id' => $option['option_value_id'],
                        'name' => $option['name'],
                        'value' => $option['value'],
                        'type' => $option['type']
                    );
                }

                $order_data['products'][] = array(
                    'product_id' => $product['product_id'],
                    'name' => $product['name'],
                    'model' => $product['model'],
                    'option' => $option_data,
                    'download' => $product['download'],
                    'quantity' => $product['quantity'],
                    'subtract' => $product['subtract'],
                    'price' => $product['price'],
                    'total' => $product['total'],
                    'tax' => $this->tax->getTax($product['price'], $product['tax_class_id']),
                    'reward' => $product['reward'],
                    'case_order_image' => ($product['case_order_image'] != '' ? $product['case_order_image'] : ($product['customer_order_image'] != '' ? $product['customer_order_image'] : '')),
                    'customer_pattern_data' => $product['customer_pattern_data'],
                    'customcase_image' => $product['customcase_image']
                );
            }

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

            if (!empty($this->session->data['vouchers'])) {
                foreach ($this->session->data['vouchers'] as $voucher) {
                    $order_data['vouchers'][] = array(
                        'description' => $voucher['description'],
                        'code' => substr(md5(mt_rand()), 0, 10),
                        'to_name' => $voucher['to_name'],
                        'to_email' => $voucher['to_email'],
                        'from_name' => $voucher['from_name'],
                        'from_email' => $voucher['from_email'],
                        'voucher_theme_id' => $voucher['voucher_theme_id'],
                        'message' => $voucher['message'],
                        'amount' => $voucher['amount']
                    );
                }
            }

            if (!isset($this->session->data['order_comment'])) {
                $this->session->data['order_comment'] = '';
            }

            if (!isset($this->session->data['survey'])) {
                $this->session->data['survey'] = '';
            }

            if (!isset($this->session->data['delivery_date'])) {
                $this->session->data['delivery_date'] = '';
            }

            if (!isset($this->session->data['delivery_time'])) {
                $this->session->data['delivery_time'] = '';
            }

            $this->session->data['comment'] = '';

            if ($this->session->data['order_comment'] != '') {
                $this->session->data['comment'] .= $this->language->get('text_order_comments') . ' ' . $this->session->data['order_comment'];
            }

            if ($this->session->data['survey'] != '') {
                $this->session->data['comment'] .= "\n\n" . $this->language->get('text_survey') . ' ' . $this->session->data['survey'];
            }

            if ($this->session->data['delivery_date'] != '') {
                $this->session->data['comment'] .= "\n\n" . $this->language->get('text_delivery') . ' ' . $this->session->data['delivery_date'];

                if ($this->session->data['delivery_time'] != '') {
                    $this->session->data['comment'] .= ' ' . $this->session->data['delivery_time'];
                }
            }

            $order_data['comment'] = $this->session->data['comment'];
            $order_data['total'] = $total;

            if (isset($this->request->cookie['tracking'])) {
                $order_data['tracking'] = $this->request->cookie['tracking'];

                $subtotal = $this->cart->getSubTotal();

                // Affiliate
                $this->load->model('affiliate/affiliate');

                $affiliate_info = $this->model_affiliate_affiliate->getAffiliateByCode($this->request->cookie['tracking']);

                if ($affiliate_info) {
                    $order_data['affiliate_id'] = $affiliate_info['affiliate_id'];
                    $order_data['commission'] = ($subtotal / 100) * $affiliate_info['commission'];
                } else {
                    $order_data['affiliate_id'] = 0;
                    $order_data['commission'] = 0;
                }

                // Marketing
                $this->load->model('checkout/marketing');

                $marketing_info = $this->model_checkout_marketing->getMarketingByCode($this->request->cookie['tracking']);

                if ($marketing_info) {
                    $order_data['marketing_id'] = $marketing_info['marketing_id'];
                } else {
                    $order_data['marketing_id'] = 0;
                }
            } else {
                $order_data['affiliate_id'] = 0;
                $order_data['commission'] = 0;
                $order_data['marketing_id'] = 0;
                $order_data['tracking'] = '';
            }

            $order_data['language_id'] = $this->config->get('config_language_id');

            $order_data['currency_id'] = $this->currency->getId($this->session->data['currency']);
            $order_data['currency_code'] = $this->session->data['currency'];
            $order_data['currency_value'] = $this->currency->getValue($this->session->data['currency']);

            $order_data['ip'] = $this->request->server['REMOTE_ADDR'];

            if (!empty($this->request->server['HTTP_X_FORWARDED_FOR'])) {
                $order_data['forwarded_ip'] = $this->request->server['HTTP_X_FORWARDED_FOR'];
            } elseif (!empty($this->request->server['HTTP_CLIENT_IP'])) {
                $order_data['forwarded_ip'] = $this->request->server['HTTP_CLIENT_IP'];
            } else {
                $order_data['forwarded_ip'] = '';
            }

            if (isset($this->request->server['HTTP_USER_AGENT'])) {
                $order_data['user_agent'] = $this->request->server['HTTP_USER_AGENT'];
            } else {
                $order_data['user_agent'] = '';
            }

            if (isset($this->request->server['HTTP_ACCEPT_LANGUAGE'])) {
                $order_data['accept_language'] = $this->request->server['HTTP_ACCEPT_LANGUAGE'];
            } else {
                $order_data['accept_language'] = '';
            }

            $this->load->model('checkout/order');

            if(!isset($this->session->data['order_id'])){
                $this->session->data['order_id'] = $this->model_checkout_order->addOrder($order_data);
            }

            $data['order_id'] = $this->session->data['order_id'];
            

            //$data['payment'] = $this->load->controller('extension/payment/' . $this->session->data['payment_method']['code']);
            //echo $data['payment'];
            
        } else {
            $data['redirect'] = $redirect;
        }

        // All variables
        $data['confirmation_page'] = $this->config->get('quickcheckout_confirmation_page');
        $data['auto_submit'] = $this->config->get('quickcheckout_auto_submit');
        $data['button_back'] = $this->language->get('button_back');
        $data['payment_target'] = html_entity_decode($this->config->get('quickcheckout_payment_target'), ENT_QUOTES);
        $data['back'] = $this->url->link('quickcheckout/checkout', '', true);

        $this->printOutput($data);

    }

    private function printOutput($json)
    {
        $this->response->addHeader('Access-Control-Allow-Origin: *');
        $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
        $this->response->addHeader('Access-Control-Max-Age: 1000');
        $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

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

    //COD

    public function codConfirm() {

        $param = array_merge($_POST, (array) json_decode(file_get_contents('php://input')));
        $data = [];
        
        if ($this->session->data['payment_method']['code'] == 'cod') {
            $this->load->model('checkout/order');
            $this->load->model('extension/payment/cod');
            if($this->model_extension_payment_cod->doubleOrderControl($this->session->data['order_id'])){
                $this->model_checkout_order->addOrderHistory($this->session->data['order_id'], $this->config->get('cod_order_status_id'));
                $data['success'] = true;
            }else{
                $data['success'] = false;
            }
           
        }else{
            $data['success'] = false;
        }

        $this->printOutput($data);
    }

    // IYZICO

    public function iyzico() {

        //https://www.deercase.com/index.php?route=checkout/odeme/gettoken


        try {
            if (!isset($this->request->get['order_id'])){
                die();
            } else {
                $this->session->data['order_id'] = $this->request->get['order_id'];
            }

            IyzipayBootstrap::init();

            $data['checkout_form_content'] = '';
            $data['error'] = '';
            $data['form_class'] = $this->config->get('iyzico_checkout_form_form_class');
            $data['continue'] = $this->url->link('checkout/success');
            $data['error_page'] = $this->url->link('checkout/error');
            $data['display_direct_confirm'] = 'no';

            $route_url = 'extension/payment/iyzico_checkout_form/callback';
            $callback_url = $this->getSiteUrl() . 'index.php?route=' . $route_url;

            $order_id = $this->session->data['order_id'];
            $unique_conversation_id = uniqid($this->order_prefix) . "_" . $order_id;

            $merchant_api_id = $this->config->get('iyzico_checkout_form_api_id_live');
            $merchant_secret_key = $this->config->get('iyzico_checkout_form_secret_key_live');

            $options = new \Iyzipay\Options();
            $options->setApiKey($merchant_api_id);
            $options->setSecretKey($merchant_secret_key);
            $options->setBaseUrl($this->base_url);

            $this->load->language('extension/payment/iyzico_checkout_form');

            if(file_exists(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') .'/template/extension/payment/iyzico_checkout_form.tpl')){
                $this->template = DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/extension/payment/iyzico_checkout_form';
            }else{
                $this->template = DIR_TEMPLATE . 'default/template/extension/payment/iyzico_checkout_form';
            }

            $this->load->model('checkout/order');
            $this->load->model('catalog/product');
            $this->load->model('catalog/category');
            $this->load->model('account/customer');
            $this->load->model('extension/extension');
            $order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);
       
            if (!in_array($order_info['currency_code'], $this->valid_currency)) {
                throw new \Exception($this->language->get('error_invalid_currency'));
            }

            $cart_total_amount = round($order_info['total'] * $order_info['currency_value'], 2);

            if ($cart_total_amount == 0) {
                $data['display_direct_confirm'] = 'yes';
                $this->response->addHeader('Content-Type: application/json');
                $this->response->setOutput(json_encode($data));
                return true;
            }

            $locale = \Iyzipay\Model\Locale::EN;
            $siteLang = explode('-', $order_info['language_code']);
            if($siteLang[0] == 'tr'){
                $locale = \Iyzipay\Model\Locale::TR;
            }

            $request = new \Iyzipay\Request\CreateCheckoutFormInitializeRequest();
            $request->setLocale($locale);
            $request->setConversationId($unique_conversation_id);

            // * 0.90
            // %10 İndirim
            if($this->config->get('promotion')['discount_percent']){
                $cart_total_amount *= 0.90;
            }

            $request->setPaidPrice($cart_total_amount);
            $request->setBasketId($unique_conversation_id);
            $request->setPaymentGroup(\Iyzipay\Model\PaymentGroup::PRODUCT);
            $request->setPaymentSource("PIYERSOFT-" . $this->iyzico_version);
            $request->setCallbackUrl($callback_url);
            $request->setCurrency($this->getCurrencyConstant($order_info['currency_code']));

            $customer_address = trim($order_info['payment_address_1'] . " " . $order_info['payment_address_2']);
            $customer_address = !empty($customer_address) ? $customer_address : "NOT PROVIDED";

            $buyer = new \Iyzipay\Model\Buyer();
            $buyer->setId($order_info['customer_id']);

            $order_info_firstname = !empty($order_info['firstname']) ? $order_info['firstname'] : "NOT PROVIDED";
            $order_info_lastname = !empty($order_info['lastname']) ? $order_info['lastname'] : "NOT PROVIDED";
            $order_info_telephone = !empty($order_info['telephone']) ? $order_info['telephone'] : "NOT PROVIDED";
            $order_info_email = !empty($order_info['email']) ? $order_info['email'] : "NOT PROVIDED";

            $buyer->setName($order_info_firstname);
            $buyer->setSurname($order_info_lastname);
            $buyer->setGsmNumber($order_info_telephone);
            $buyer->setEmail($order_info_email);
            $buyer->setRegistrationAddress($customer_address);

            $order_info_payment_zone = !empty($order_info['payment_zone']) ? $order_info['payment_zone'] : "NOT PROVIDED";
            $order_info_payment_city = !empty($order_info['payment_city']) ? $order_info['payment_city'] : $order_info_payment_zone;
            $order_info_payment_country = !empty($order_info['payment_country']) ? $order_info['payment_country'] : "NOT PROVIDED";
            $order_info_payment_postcode = !empty($order_info['payment_postcode']) ? $order_info['payment_postcode'] : "NOT PROVIDED";
            $order_info_ip = !empty($order_info['ip']) ? $order_info['ip'] : "NOT PROVIDED";

            $buyer->setCity($order_info_payment_zone);
            $buyer->setCountry($order_info_payment_country);
            $buyer->setZipCode($order_info_payment_postcode);
            $buyer->setIp($order_info_ip);

            $customer_identity_number = str_pad($order_info['customer_id'], 11, '0', STR_PAD_LEFT);
            $buyer->setIdentityNumber($customer_identity_number);

            if ($order_info['customer_id'] > 0) {
                $customer_query = $this->db->query("SELECT * FROM ps_customer WHERE customer_id = '" . (int) $order_info['customer_id'] . "' AND status = '1'");
                $added_date = !empty($customer_query->row['date_added']) ? $customer_query->row['date_added'] : "NOT PROVIDED";
                $buyer->setRegistrationDate($added_date);
            }
            $request->setBuyer($buyer);

            $billing_address = new \Iyzipay\Model\Address();
            $billing_address->setContactName($order_info_firstname);
            $billing_address->setCity($order_info_payment_zone);
            $billing_address->setCountry($order_info_payment_country);
            $billing_address->setAddress($customer_address);
            $billing_address->setZipCode($order_info_payment_postcode);
            $request->setBillingAddress($billing_address);

            $customer_shipping_address1 = !empty($order_info['shipping_address_1']) ? $order_info['shipping_address_1'] : $order_info['payment_address_1'];
            $customer_shipping_address2 = !empty($order_info['shipping_address_2']) ? $order_info['shipping_address_2'] : $order_info['payment_address_2'];
            $customer_shipping_address = trim($customer_shipping_address1 . " " . $customer_shipping_address2);
            $customer_shipping_address = !empty($customer_shipping_address) ? $customer_shipping_address : "NOT PROVIDED";
            $shipping_name = !empty($order_info['shipping_firstname']) ? $order_info['shipping_firstname'] : $order_info_firstname;
            $shipping_zone = !empty($order_info['shipping_zone']) ? $order_info['shipping_zone'] : $order_info_payment_zone;
            $shipping_city = !empty($order_info['shipping_city']) ? $order_info['shipping_city'] : $shipping_zone;
            $shipping_country = !empty($order_info['shipping_country']) ? $order_info['shipping_country'] : $order_info_payment_country;
            $shipping_zip_code = !empty($order_info['shipping_postcode']) ? $order_info['shipping_postcode'] : $order_info_payment_postcode;

            $shipping_address = new \Iyzipay\Model\Address();
            $shipping_address->setContactName($shipping_name);
            $shipping_address->setCity($shipping_city);
            $shipping_address->setCountry($shipping_country);
            $shipping_address->setAddress($customer_shipping_address);
            $shipping_address->setZipCode($shipping_zip_code);
            $request->setShippingAddress($shipping_address);

            $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);
            $allowed_order_total_extensions = array(
                'reward',
                'shipping',
                'coupon',
                'voucher'
            );
            $allowed_order_total_extensions_sort = array();

            foreach ($results as $result) {
                if ($this->config->get($result['code'] . '_status') && in_array($result['code'], $allowed_order_total_extensions)) {
                    $allowed_order_total_extensions_sort[] = $result['code'];
                }
            }

            $items = array();
            $products = $this->cart->getProducts();
            $product_prices = $total_discounts = $voucher_amount = $voucher_per_item = $applied_voucher_amount = 0;
            $shipping_amount = $total_shipping_charge = $points_total = 0;
            $has_coupon = $has_voucher = $has_rewards = $has_shipping =  false;
            $coupon_info = $voucher_info = $shipping_info = array();
            $purchase_voucher_amount = 0;

            $sub_total = $this->cart->getSubTotal();

            if (isset($this->session->data['coupon'])) {
                $has_coupon = true;
                $coupon = $this->session->data['coupon'];

                $this->load->model('extension/total/coupon');
                $coupon_info = $this->model_extension_total_coupon->getCoupon($coupon);

                if ($coupon_info['type'] == 'F') {
                    $coupon_info['discount'] = min($coupon_info['discount'], $sub_total);
                }
            }

            if (isset($this->session->data['voucher'])) {
                $has_voucher = true;

                $voucher = $this->session->data['voucher'];
                
                $this->load->model('extension/total/voucher');
                $voucher_info = $this->model_extension_total_voucher->getVoucher($voucher);
            
                $voucher_info['amount'] = min($voucher_info['amount'], $sub_total);
            }

            $points = $this->customer->getRewardPoints();

            if (isset($this->session->data['reward']) && $this->session->data['reward'] <= $points) {
                $has_rewards = true;
                foreach ($this->cart->getProducts() as $product) {
                    if ($product['points']) {
                        $points_total += $product['points'];
                    }
                }
            }

            if ($this->cart->hasShipping() && isset($this->session->data['shipping_method'])) {
                $has_shipping = true;
                $shipping_info = $this->session->data['shipping_method'];
                $shipping_amount = $shipping_info['cost'];
                if ($shipping_info['tax_class_id']) {
                    $shipping_info['tax'] = $this->tax->getRates($shipping_info['cost'], $shipping_info['tax_class_id']);
                }

            }

            if (!empty($this->session->data['vouchers'])) {
                foreach ($this->session->data['vouchers'] as $key => $voucher) {
                    $purchase_voucher_amount = round($voucher['amount'], 2);
                    $item = new \Iyzipay\Model\BasketItem();
                    $item->setId($key);
                    $item->setName($voucher['description']);
                    $item->setItemType(\Iyzipay\Model\BasketItemType::VIRTUAL);
                    $item->setCategory1("GIFT VOUCHERS");
                    $total_product_price = $voucher['amount'];
                    $total_product_price *= $order_info['currency_value'];
                    $total_product_price = round($total_product_price, 2);
                    $product_prices += $total_product_price;
                    $item->setPrice($total_product_price);
                    $items[] = $item;
                }
            }

            $product_name = '';
            $product_id = array();

            foreach ($products as $product) {
                $product_id[] = !empty($product['product_id']) ? $product['product_id'] : 0;
                $product_name = !empty($product['name']) ? $product['name'] : "NOT PROVIDED";
            }

            $exchange_rate = $this->currency->getValue($order_info['currency_code']);
            $tax_total = $this->cart->getTaxes();
            foreach($tax_total as $value) {
                $sub_total += $value;
            }

            $sub_total += $shipping_amount * 1.08;
            $sub_total -= $total_discounts;
            $sub_total += $purchase_voucher_amount;
            $sub_total *= $exchange_rate;
            $sub_total = round($sub_total, 2);

            $item = new \Iyzipay\Model\BasketItem();
            $item->setId(implode(',', $product_id));
            $item->setPrice($sub_total);
            $item->setName($product_name);
            $item->setCategory1('NOT PROVIDED');
            $item->setItemType(\Iyzipay\Model\BasketItemType::PHYSICAL);

            $items[] = $item;

            $items = array_values($items);
            $request->setPrice($sub_total);
            $request->setBasketItems($items);


            if (function_exists('curl_version')) {

                $this->load->model('extension/payment/iyzico_checkout_form');
                $save_data_array = array(
                    'order_id' => $order_id,
                    'item_id' => 0,
                    'transaction_status' => 'in process',
                    'date_created' => date('Y-m-d H:i:s'),
                    'date_modified' => date('Y-m-d H:i:s'),
                    'api_request' => $request->toJsonString(),
                    'api_response' => '',
                    'request_type' => 'payment_form_initialization',
                    'note' => ''
                );
                $create_order_entry_id = $this->model_extension_payment_iyzico_checkout_form->createOrderEntry($save_data_array);

                $response = \Iyzipay\Model\CheckoutFormInitialize::create($request, $options);

                $update_data_array = array(
                    'date_modified' => date('Y-m-d H:i:s'),
                    'api_response' => $response->getRawResult(),
                    'transaction_status' => $response->getStatus(),
                    'processing_timestamp' => date('Y-m-d H:i:s', $response->getSystemTime() / 1000)
                );

                $this->model_extension_payment_iyzico_checkout_form->updateOrderEntry($update_data_array, $create_order_entry_id);

                $data['siteUrl'] = $this->getSiteUrl();

                if ($response->getStatus() == "success") {
                    $data['checkout_form_content'] = $response->getCheckoutFormContent();
                } else {
                    $data['error'] = !is_null($response->getErrorMessage()) ? $response->getErrorMessage() : $response->getErrorCode();
                }
            } else {
                $data['error'] = $this->language->get("Error_message_curl");
            }
        } catch (\Exception $exc) {
            $data['error'] = $exc->getMessage();
        }

        $this->load->language('extension/payment/iyzico_checkout_form');

        $data['cart_total'] = $sub_total;
        $data['code'] = $this->language->get('code');
        $data['form_class'] = $this->config->get('iyzico_checkout_form_form_class');
        $data['text_credit_card'] = $this->language->get('text_credit_card');
        $data['text_wait'] = $this->language->get('text_wait');
        $data['button_confirm'] = $this->language->get('button_confirm');
        $data['continue'] = $this->url->link('checkout/success');
        $data['error_page'] = $this->url->link('checkout/error');

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



    }

    public function getSiteUrl() {
        if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) {
            $site_url = is_null($this->config->get('config_ssl')) ? HTTPS_SERVER : $this->config->get('config_ssl');
        } else {
            $site_url = is_null($this->config->get('config_url')) ? HTTP_SERVER : $this->config->get('config_url');
        }
        return $site_url;
    }

    public function getServerConnectionSlug() {
        if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) {
            $connection = 'SSL';
        } else {
            $connection = 'NONSSL';
        }
        return $connection;
    }

    public function callback() {


        $server_conn_slug = $this->getServerConnectionSlug();
        $this->load->language('extension/payment/iyzico_checkout_form');
        $this->load->model('extension/payment/iyzico_checkout_form');
        $this->load->model('checkout/order');
        $postData = $this->request->post;

        $message = '';
        $get_auth_table_id = 0;


        try {

            IyzipayBootstrap::init();


            $merchant_api_id = $this->config->get('iyzico_checkout_form_api_id_live');
            $merchant_secret_key = $this->config->get('iyzico_checkout_form_secret_key_live');



            $options = new \Iyzipay\Options();
            $options->setApiKey($merchant_api_id);
            $options->setSecretKey($merchant_secret_key);
            $options->setBaseUrl($this->base_url);

            $request = new \Iyzipay\Request\RetrieveCheckoutFormRequest();
            $request->setLocale(\Iyzipay\Model\Locale::TR);
            $request->setToken($postData['token']);

            $response = \Iyzipay\Model\CheckoutForm::retrieve($request, $options);

            $transaction = array();

            $basketId = $response->getBasketId();
            $paymentId = $response->getPaymentId();

            $explode_basket_id = explode("_", $basketId);
            $response_order_id = end($explode_basket_id);

            $order_id = $response_order_id;

            if (empty($postData['token'])) {
                throw new \Exception($this->language->get('invalid_request'));
            }

            $log = new Log('iyzico/'.$order_id . "_IyzicoCallbackPostDataLogs.txt");

            $log->write($order_id . " callback başladı ");

            $log->write($order_id . " Try bloğuna girildi ");

            $log->write($postData);
            $log->write($order_id . " Iyzicodan gelen post verileri yazdırılıldı ");

            $save_data_array = array(
                'order_id' => 0,
                'transaction_status' => '',
                'date_created' => date('Y-m-d H:i:s'),
                'date_modified' => date('Y-m-d H:i:s'),
                'api_request' => '',
                'api_response' => json_encode($postData),
                'request_type' => 'post_callback',
                'processing_timestamp' => date('Y-m-d H:i:s'),
                'note' => 'callback'
            );
            $post_callback_id = $this->model_extension_payment_iyzico_checkout_form->createOrderEntry($save_data_array);

            $log->write($order_id . " ps_iyzico_order tablosuna veri yazıldı ID: " . $post_callback_id);

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

            $save_data_array = array(
                'order_id' => 0,
                'item_id' => 0,
                'transaction_status' => 'in process',
                'date_created' => date('Y-m-d H:i:s'),
                'date_modified' => date('Y-m-d H:i:s'),
                'api_request' => $request->toJsonString(),
                'api_response' => '',
                'request_type' => 'get_auth',
                'note' => 'callback'
            );
            $get_auth_table_id = $this->model_extension_payment_iyzico_checkout_form->createOrderEntry($save_data_array);

            $log->write($order_id . " ps_iyzico_order tablosuna 2. veri yazıldı ID: " . $get_auth_table_id);

            $response = \Iyzipay\Model\CheckoutForm::retrieve($request, $options);

            $log->write($order_id . " CheckoutForm::retrieve sonucu aşağıdadır ");
            $log->write($response);
            $log->write($order_id . " CheckoutForm::retrieve sonucu yukarıdadır ");

            $update_data_array = array(
                'date_modified' => date('Y-m-d H:i:s'),
                'api_response' => $response->getRawResult(),
                'transaction_status' => $response->getStatus(),
                'processing_timestamp' => date('Y-m-d H:i:s', $response->getSystemTime() / 1000)
            );
            $this->model_extension_payment_iyzico_checkout_form->updateOrderEntry($update_data_array, $get_auth_table_id);

            $log->write($order_id . " ps_iyzico_order tablosunda veri güncellendi ID: " . $get_auth_table_id);

            if ($response->getStatus() == "failure") {
                $log->write($order_id . " sonuç : failure ");
                $log->write($response->getErrorMessage());
                throw new \Exception($response->getErrorMessage());
            }

            if ($response->getPaymentStatus() == "FAILURE") {
                $log->write($order_id . " sonuç : FAILURE ");
                $log->write($response->getErrorMessage());
                throw new \Exception($response->getErrorMessage());
            }

            $basketId = $response->getBasketId();
            $paymentId = $response->getPaymentId();

            if (!empty($paymentId)) {
                $message .= 'Payment ID: ' . $paymentId . "\n";
            }

            $explode_basket_id = explode("_", $basketId);
            $response_order_id = end($explode_basket_id);

            $update_data_array = array(
                'order_id' => $response_order_id,
                'date_modified' => date('Y-m-d H:i:s'),
                'processing_timestamp' => date('Y-m-d H:i:s', $response->getSystemTime() / 1000)
            );
            $this->model_extension_payment_iyzico_checkout_form->updateOrderEntry($update_data_array, $get_auth_table_id);
            $log->write($order_id . " ps_iyzico_order tablosunda get_auth_table_id numarasına göre güncelleme yapıldı ID: " . $get_auth_table_id);

            $this->model_extension_payment_iyzico_checkout_form->updateOrderEntry($update_data_array, $post_callback_id);
            $log->write($order_id . " ps_iyzico_order tablosunda post_callback_id numarasına göre güncelleme yapıldı ID: " . $post_callback_id);

            if (empty($response_order_id) || $response_order_id != $order_id) {
                throw new \Exception($this->language->get('invalid_order'));
            }

            $order_info = $this->model_checkout_order->getOrder($response_order_id);

            $log->write($order_id . " Sipariş detayı çekildi ");
            $log->write($order_info);

            if (!empty($order_info['order_status_id']) && $order_info['order_status'] != null) {
                throw new \Exception($this->language->get('order_already_exists'));
            }

            $installment = $response->getInstallment();
            if ($installment > 1) {
                $log->write($order_id . " Taksitli işlem için kayıt başladı");

                $this->load->model('checkout/order');
                $order_total = (array) $this->db->query("SELECT * FROM ps_order_total WHERE order_id = '" . (int) $order_id . "' AND code = 'total' ");
                $last_sort_value = $order_total['row']['sort_order'] - 1;
                $exchange_rate = $this->currency->getValue($order_info['currency_code']);
                $new_amount = str_replace(',', '', $response->getPaidPrice());
                $old_amount = str_replace(',', '', $order_info['total'] * $order_info['currency_value']);
                $installment_fee_variation = ($new_amount - $old_amount) / $exchange_rate;
                $this->db->query("INSERT INTO ps_order_total SET order_id = '" .
                    (int) $order_id . "',code = '" . $this->db->escape('iyzico_checkout_form_fee') .
                    "',  title = '" . $this->db->escape($this->language->get('installment_charge')) . "' , `value` = '" .
                    (float) $installment_fee_variation . "', sort_order = '" . (int) $last_sort_value . "'");


                $log->write($order_id . " ps_order_total tablosuna kayıt girildi ");

                //$order_total_data = (array) $this->db->query("SELECT * FROM ps_order_total WHERE order_id = '" . (int) $order_id . "' AND code != 'total' ");
                $order_total_data = (array) $this->db->query("SELECT * FROM ps_order_total 
                                WHERE order_id = '" . (int) $order_id . "' 
                                AND code != 'total'
                                AND code != 'coupon'
                                AND code != 'campaign_price_total' ");
                $calculate_total = 0;
                foreach ($order_total_data['rows'] as $row) {
                    $calculate_total += $row['value'];
                }

                $log->write($order_id . " Taksitli işlem için sipariş toplamları eklendi");

                $this->db->query("UPDATE ps_order_total SET  `value` = '" . (float) $calculate_total . "' WHERE order_id = '$order_id' AND code = 'total' ");

                $this->db->query("UPDATE ps_order SET total = '" . $calculate_total . "' WHERE order_id = '" . (int) $order_id . "'");

                $this->model_checkout_order->addOrderHistory($this->session->data['order_id'], $this->config->get('iyzico_checkout_form_order_status_id'), $message, false);

                $log->write($order_id . " Taksitli işlem için sipariş geçmişi eklendi");

                $comment = $response->getCardFamily() . ' - ' . $response->getInstallment() . '  Taksit';
                $this->db->query("INSERT INTO ps_order_history SET order_id = '" . (int) $order_id . "', order_status_id = '" .
                    $this->config->get('iyzico_checkout_form_order_status_id') . "', notify = '0', comment = '" .
                    $this->db->escape($comment) . "', date_added = NOW()");

                $log->write($order_id . " ps_order_history tablosuna kayıt girildi ");
            } else {
                $log->write($order_id . " Tek çekim için işlem başladı");
                $this->model_checkout_order->addOrderHistory($response_order_id, $this->config->get('iyzico_checkout_form_order_status_id'), $message, false);
                $log->write($order_id . " Tek çekim için sipariş geçmişi eklendi");
            }

            $item_transactions = $response->getPaymentItems();

            $log->write($order_id . " Iyzicodan işlem sonucu geldi aşağıdadır. ");
            $log->write($item_transactions);

            foreach ($item_transactions as $item_transaction) {
                $item_data_array = array(
                    'order_id' => $order_id,
                    'paid_price' => $item_transaction->getPaidPrice(),
                    'item_id' => $item_transaction->getItemId(),
                    'payment_transaction_id' => $item_transaction->getPaymentTransactionId(),
                    'total_refunded' => 0
                );
                $this->model_extension_payment_iyzico_checkout_form->createRefundItemEntry($item_data_array);
            }

            $log->write($order_id . " Success sayfasına yönleniyoruz ");
            $this->response->redirect($this->url->link('checkout/success', '', $server_conn_slug));

        } catch (\Exception $ex) {

            $log->write($order_id . " Catch bloğuna girildi ");

            $resp_msg = $ex->getMessage();

            $log->write($order_id . " resp_msg bilgisi aşağıdadır ");
            $log->write($resp_msg);

            $resp_msg = !empty($resp_msg) ? $resp_msg : $this->language->get('invalid_request');
            if (!empty($get_auth_table_id)) {
                $update_data_array = array(
                    'note' => $resp_msg . ' Callback',
                    'date_modified' => date('Y-m-d H:i:s'),
                );
                $this->model_extension_payment_iyzico_checkout_form->updateOrderEntry($update_data_array, $get_auth_table_id);
            }

            $this->session->data['error'] = $resp_msg;

            $log->write($order_id . " sorun oluştuğu için tekrar ödeme sayfanına yönleniyoruz ");

            $this->response->redirect($this->url->link('checkout/checkout', '', $server_conn_slug));
        }

        $log->write($order_id . " try ve catch bloklarına girilemedi error sayfasına gidiyoruz ");

        $this->response->redirect($this->url->link('checkout/error', '', $server_conn_slug));
    }

    public function webhooks()
    {

        //https://www.deercase.com/index.php?route=extension/payment/iyzico_checkout_form/webhooks


        $param = array_merge($_POST, (array) json_decode(file_get_contents('php://input')));


        if($param){


            $paymentConversationId = explode('_', $param['paymentConversationId']);

            $order_id = $paymentConversationId[2];

            $log = new Log("iyzico_webhooks/". $order_id ."_IyzicoWebHookLog.txt");
            $log->write($param);

            $server_conn_slug = $this->getServerConnectionSlug();
            $this->load->language('extension/payment/iyzico_checkout_form');
            $this->load->model('extension/payment/iyzico_checkout_form');
            $this->load->model('checkout/order');
            $postData = $param;
            $message = '';
            $get_auth_table_id = 0;
            try {
                $save_data_array = array(
                    'order_id' => 0,
                    'transaction_status' => '',
                    'date_created' => date('Y-m-d H:i:s'),
                    'date_modified' => date('Y-m-d H:i:s'),
                    'api_request' => '',
                    'api_response' => json_encode($postData),
                    'request_type' => 'post_callback',
                    'processing_timestamp' => date('Y-m-d H:i:s'),
                    'note' => 'webhooks'
                );
                $post_callback_id = $this->model_extension_payment_iyzico_checkout_form->createOrderEntry($save_data_array);

                if (empty($postData['token'])) {
                    throw new \Exception($this->language->get('invalid_request'));
                }

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

                IyzipayBootstrap::init();

                $merchant_api_id = $this->config->get('iyzico_checkout_form_api_id_live');
                $merchant_secret_key = $this->config->get('iyzico_checkout_form_secret_key_live');

                $options = new \Iyzipay\Options();
                $options->setApiKey($merchant_api_id);
                $options->setSecretKey($merchant_secret_key);
                $options->setBaseUrl($this->base_url);

                $request = new \Iyzipay\Request\RetrieveCheckoutFormRequest();
                $request->setLocale(\Iyzipay\Model\Locale::TR);
                $request->setToken($postData['token']);

                $save_data_array = array(
                    'order_id' => 0,
                    'item_id' => 0,
                    'transaction_status' => 'in process',
                    'date_created' => date('Y-m-d H:i:s'),
                    'date_modified' => date('Y-m-d H:i:s'),
                    'api_request' => $request->toJsonString(),
                    'api_response' => '',
                    'request_type' => 'get_auth',
                    'note' => 'webhooks'
                );
                $get_auth_table_id = $this->model_extension_payment_iyzico_checkout_form->createOrderEntry($save_data_array);

                $response = \Iyzipay\Model\CheckoutForm::retrieve($request, $options);

                $update_data_array = array(
                    'date_modified' => date('Y-m-d H:i:s'),
                    'api_response' => $response->getRawResult(),
                    'transaction_status' => $response->getStatus(),
                    'processing_timestamp' => date('Y-m-d H:i:s', $response->getSystemTime() / 1000)
                );
                $this->model_extension_payment_iyzico_checkout_form->updateOrderEntry($update_data_array, $get_auth_table_id);


                if ($response->getStatus() == "failure") {
                    throw new \Exception($response->getErrorMessage());
                }

                if ($response->getPaymentStatus() == "FAILURE") {
                    throw new \Exception($response->getErrorMessage());
                }

                $basketId = $response->getBasketId();
                $paymentId = $response->getPaymentId();

                if (!empty($paymentId)) {
                    $message .= 'Payment ID: ' . $paymentId . "\n";
                }

                $explode_basket_id = explode("_", $basketId);
                $response_order_id = end($explode_basket_id);

                $update_data_array = array(
                    'order_id' => $response_order_id,
                    'date_modified' => date('Y-m-d H:i:s'),
                    'processing_timestamp' => date('Y-m-d H:i:s', $response->getSystemTime() / 1000)
                );

                $this->model_extension_payment_iyzico_checkout_form->updateOrderEntry($update_data_array, $get_auth_table_id);

                $this->model_extension_payment_iyzico_checkout_form->updateOrderEntry($update_data_array, $post_callback_id);

                if (empty($response_order_id) || $response_order_id != $order_id) {
                    throw new \Exception($this->language->get('invalid_order'));
                }

                $order_info = $this->model_checkout_order->getOrder($response_order_id);

                if (!empty($order_info['order_status_id']) && $order_info['order_status'] != null) {
                    throw new \Exception($this->language->get('order_already_exists'));
                }

                $installment = $response->getInstallment();
                if ($installment > 1) {

                    $this->load->model('checkout/order');
                    $order_total = (array) $this->db->query("SELECT * FROM ps_order_total WHERE order_id = '" . (int) $order_id . "' AND code = 'total' ");
                    $last_sort_value = $order_total['row']['sort_order'] - 1;
                    $exchange_rate = $this->currency->getValue($order_info['currency_code']);
                    $new_amount = str_replace(',', '', $response->getPaidPrice());
                    $old_amount = str_replace(',', '', $order_info['total'] * $order_info['currency_value']);
                    $installment_fee_variation = ($new_amount - $old_amount) / $exchange_rate;
                    $this->db->query("INSERT INTO ps_order_total SET order_id = '" .
                        (int) $order_id . "',code = '" . $this->db->escape('iyzico_checkout_form_fee') .
                        "',  title = '" . $this->db->escape($this->language->get('installment_charge')) . "' , `value` = '" .
                        (float) $installment_fee_variation . "', sort_order = '" . (int) $last_sort_value . "'");


                    $order_total_data = (array) $this->db->query("SELECT * FROM ps_order_total 
                                WHERE order_id = '" . (int) $order_id . "' 
                                AND code != 'total'
                                AND code != 'coupon'
                                AND code != 'campaign_price_total' ");
                    $calculate_total = 0;
                    foreach ($order_total_data['rows'] as $row) {
                        $calculate_total += $row['value'];
                    }


                    $this->db->query("UPDATE ps_order_total SET  `value` = '" . (float) $calculate_total . "' WHERE order_id = '$order_id' AND code = 'total' ");
                    $this->db->query("UPDATE ps_order SET total = '" . $calculate_total . "' WHERE order_id = '" . (int) $order_id . "'");
                    $this->model_checkout_order->addOrderHistory($this->session->data['order_id'], $this->config->get('iyzico_checkout_form_order_status_id'), $message, false);

                    $comment = $response->getCardFamily() . ' - ' . $response->getInstallment() . '  Taksit';
                    $this->db->query("INSERT INTO ps_order_history SET order_id = '" . (int) $order_id . "', order_status_id = '" .
                    $this->config->get('iyzico_checkout_form_order_status_id') . "', notify = '0', comment = '" .
                    $this->db->escape($comment) . "', date_added = NOW()");
                } else {
                    $this->model_checkout_order->addOrderHistory($response_order_id, $this->config->get('iyzico_checkout_form_order_status_id'), $message, false);
                }

                $item_transactions = $response->getPaymentItems();


                foreach ($item_transactions as $item_transaction) {
                    $item_data_array = array(
                        'order_id' => $order_id,
                        'paid_price' => $item_transaction->getPaidPrice(),
                        'item_id' => $item_transaction->getItemId(),
                        'payment_transaction_id' => $item_transaction->getPaymentTransactionId(),
                        'total_refunded' => 0
                    );
                    $this->model_extension_payment_iyzico_checkout_form->createRefundItemEntry($item_data_array);
                }

                $this->response->redirect($this->url->link('checkout/success', '', $server_conn_slug));

            } catch (\Exception $ex) {

                $resp_msg = $ex->getMessage();

                $resp_msg = !empty($resp_msg) ? $resp_msg : $this->language->get('invalid_request');
                if (!empty($get_auth_table_id)) {
                    $update_data_array = array(
                        'note' => $resp_msg . ' Webhooks',
                        'date_modified' => date('Y-m-d H:i:s'),
                    );
                    $this->model_extension_payment_iyzico_checkout_form->updateOrderEntry($update_data_array, $get_auth_table_id);
                }

                $this->session->data['error'] = $resp_msg;

                $this->response->redirect($this->url->link('checkout/checkout', '', $server_conn_slug));
            }


            $this->response->redirect($this->url->link('checkout/error', '', $server_conn_slug));


        }




        if (isset($this->request->server['HTTP_ORIGIN'])) {
            $this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
            $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
            $this->response->addHeader('Access-Control-Max-Age: 1000');
            $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
        }

    }

    public function error() {

        if(isset($this->session->data['order_id'])){
            $order_id = $this->session->data['order_id'];
            $log = new Log('iyzico/'.$order_id . "_IyzicoErrorPostDataLogs.txt");
            $log->write($order_id . " hataya düşmüş sipariş ");
        }else{
            $log = new Log('iyzico/'."_IyzicoErrorPostDataLogs.txt");
            $log->write("Hataya düşen işlem.");
        }


        $this->language->load('extension/payment/iyzico_checkout_form');
        $this->document->setTitle($this->language->get('heading_title'));
        $data['breadcrumbs'] = array();
        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/home'),
            'separator' => false
        );

        if (isset($this->request->get['route'])) {
            $data = $this->request->get;
            unset($data['_route_']);
            $route = $data['route'];
            unset($data['route']);
            $url = '';
            if ($data) {
                $url = '&' . urldecode(http_build_query($data, '', '&'));
            }

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

        if (!empty($error['response']['state']) && $error['response']['state'] == 'failed') {
            $data['heading_title'] = "Payment error...";
            $data['text_error'] = $error['response']['error_message'];
        }

        if (VERSION >= '2.2.0.0'){
            $template_url = 'error/not_found.tpl';
        } else {
            $template_url = 'default/template/error/not_found.tpl';
        }

        $data['button_continue'] = $this->language->get('button_continue');
        $this->response->addHeader($this->request->server['SERVER_PROTOCOL'] . '/1.1 404 Not Found');
        $data['continue'] = $this->url->link('checkout/checkout');

        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 = $template_url;
        }

        $this->children = array(
            'common/column_left',
            'common/column_right',
            'common/content_top',
            'common/content_bottom',
            'common/footer',
            'common/header'
        );

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


    }

    public function confirm() {

        $order_id = $this->session->data['order_id'];

        $log = new Log('iyzico/'.$order_id . "_IyzicoConfirmPostDataLogs.txt");

        $log->write($order_id . " confirm başladı ");

        $server_conn_slug = $this->getServerConnectionSlug();
        if ($this->session->data['payment_method']['code'] == 'iyzico_checkout_form') {
            if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {

                $this->load->model('checkout/order');
                $this->load->model('extension/payment/iyzico_checkout_form');
                $order_id = $this->session->data['order_id'];
                $order_info = $this->model_checkout_order->getOrder($order_id);

                if (!empty($order_info['order_status_id']) && $order_info['order_status'] != null) {
                    throw new \Exception($this->language->get('order_already_exists'));
                }

                $cart_total_amount = round($order_info['total'] * $order_info['currency_value'], 2);
                if ($cart_total_amount == 0) {
                    $save_data_array = array(
                        'order_id' => $order_id,
                        'item_id' => 0,
                        'transaction_status' => 'success',
                        'date_created' => date('Y-m-d H:i:s'),
                        'date_modified' => date('Y-m-d H:i:s'),
                        'processing_timestamp' => date('Y-m-d H:i:s'),
                        'api_request' => '',
                        'api_response' => '',
                        'request_type' => 'get_auth',
                        'note' => 'Confirm'
                    );
                    $this->model_extension_payment_iyzico_checkout_form->createOrderEntry($save_data_array);

                    $this->model_checkout_order->addOrderHistory($order_id, $this->config->get('iyzico_checkout_form_order_status_id'));

                    $log->write($save_data_array);

                    echo true;
                } else {
                    echo false;
                }
            } else {
                $server_conn_slug = $this->getServerConnectionSlug();
                $this->response->redirect($this->url->link('checkout/error', '', $server_conn_slug));
            }
        } else {
            $this->response->redirect($this->url->link('checkout/error', '', $server_conn_slug));
        }
        exit();
    }

    private function getCurrencyConstant($currencyCode){
        $currency = \Iyzipay\Model\Currency::TL;
        switch($currencyCode){
            case "TRY":
                $currency = \Iyzipay\Model\Currency::TL;
                break;
            case "USD":
                $currency = \Iyzipay\Model\Currency::USD;
                break;
            case "GBP":
                $currency = \Iyzipay\Model\Currency::GBP;
                break;
            case "EUR":
                $currency = \Iyzipay\Model\Currency::EUR;
                break;
            case "IRR":
                $currency = \Iyzipay\Model\Currency::IRR;
                break;
        }
        return $currency;
    }

    private function setcookieSameSite($name, $value, $expire, $path, $domain, $secure, $httponly) {

        if (PHP_VERSION_ID < 70300) {
            setcookie($name, $value, $expire, "$path; samesite=None", $domain, $secure, $httponly);
        }
        else {
            setcookie($name, $value, [
                'expires' => $expire,
                'path' => $path,
                'domain' => $domain,
                'samesite' => 'None',
                'secure' => $secure,
                'httponly' => $httponly,
            ]);
        }
    }

    // IYZICO

    public function pay() {
        $data = $this->request->post;

        //var_dump($data); die();
        $order_id = $data['order_id'];

        if(empty($order_id)) {
            $json = [
                'status' => 'error',
                'message' => 'Sipariş numarası bulunamadı.'
            ];
            $this->response->addHeader('Content-Type: application/json');
            $this->response->setOutput(json_encode($json));
        }

        $total_data = array(
            'total' => &$total
        );

        if ($this->config->get('total_status')) {
            $this->load->model('extension/total/total');
            $this->{'model_extension_total_total'}->getTotal($total_data);
        }
    
        IyzipayBootstrap::init();

        $unique_conversation_id = uniqid($this->order_prefix) . "_" . $order_id;
        $this->session->data['conversation_id'] = $unique_conversation_id;

        $options = $this->getIyzicoOptions();
        
        $this->load->model('checkout/order');
        $order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);

        $totals = $this->getCartTotals();
        foreach ($totals as $total) {
            if($total['code']=='total'){
                $total_amount = $total['value'];
            }
        }

        $cart_total_amount = round($total_amount * $order_info['currency_value'], 2);

        $customer_address = trim($order_info['payment_address_1'] . " " . $order_info['payment_address_2']);
        $customer_address = !empty($customer_address) ? $customer_address : "NOT PROVIDED";
        
        $order_info_firstname = !empty($order_info['firstname']) ? $order_info['firstname'] : "NOT PROVIDED";
        $order_info_lastname = !empty($order_info['lastname']) ? $order_info['lastname'] : "NOT PROVIDED";
        $order_info_telephone = !empty($order_info['telephone']) ? $order_info['telephone'] : "NOT PROVIDED";
        $order_info_email = !empty($order_info['email']) ? $order_info['email'] : "notfound@deercase.com";

        $order_info_payment_zone = !empty($order_info['payment_zone']) ? $order_info['payment_zone'] : "NOT PROVIDED";
        $order_info_payment_city = !empty($order_info['payment_city']) ? $order_info['payment_city'] : $order_info_payment_zone;
        $order_info_payment_country = !empty($order_info['payment_country']) ? $order_info['payment_country'] : "NOT PROVIDED";
        $order_info_payment_postcode = !empty($order_info['payment_postcode']) ? $order_info['payment_postcode'] : "NOT PROVIDED";
        $order_info_ip = !empty($order_info['ip']) ? $order_info['ip'] : "NOT PROVIDED";

        $order_customer_id = !empty($order_info['customer_id']) ? $order_info['customer_id'] : 0;
        $customer_identity_number = !empty($order_info['tc']) ? $order_info['tc'] : str_pad($order_info['customer_id'], 11, '0', STR_PAD_LEFT);

        $customer_shipping_address1 = !empty($order_info['shipping_address_1']) ? $order_info['shipping_address_1'] : $order_info['payment_address_1'];
        $customer_shipping_address2 = !empty($order_info['shipping_address_2']) ? $order_info['shipping_address_2'] : $order_info['payment_address_2'];
        $customer_shipping_address = trim($customer_shipping_address1 . " " . $customer_shipping_address2);
        $customer_shipping_address = !empty($customer_shipping_address) ? $customer_shipping_address : "NOT PROVIDED";
        $shipping_name = !empty($order_info['shipping_firstname']) ? $order_info['shipping_firstname'] : $order_info_firstname;
        $shipping_zone = !empty($order_info['shipping_zone']) ? $order_info['shipping_zone'] : $order_info_payment_zone;
        $shipping_city = !empty($order_info['shipping_city']) ? $order_info['shipping_city'] : $shipping_zone;
        $shipping_country = !empty($order_info['shipping_country']) ? $order_info['shipping_country'] : $order_info_payment_country;
        $shipping_zip_code = !empty($order_info['shipping_postcode']) ? $order_info['shipping_postcode'] : $order_info_payment_postcode;

        if ($cart_total_amount == 0) {
            $data['display_direct_confirm'] = 'yes';
            $this->response->addHeader('Content-Type: application/json');
            $this->response->setOutput(json_encode($data));
            return true;
        }

        $items = [];
        $product_name = '';
        $product_id = array();
        $products = $this->cart->getProducts();
        foreach ($products as $product) {
            $product_id[] = !empty($product['product_id']) ? $product['product_id'] : 0;
            $product_name = !empty($product['name']) ? $product['name'] : "NOT PROVIDED";
        }

        $locale = \Iyzipay\Model\Locale::EN;
        $siteLang = explode('-', $order_info['language_code']);
        if($siteLang[0] == 'tr'){
            $locale = \Iyzipay\Model\Locale::TR;
        }

        $installment_number = $data['installmentNumber'] ? $data['installmentNumber'] : 1;
        $card_number = trim($data['number']);
        $cvc = trim($data['cvc']);

        if($installment_number) {
            $request = new \Iyzipay\Request\RetrieveInstallmentInfoRequest();
            $request->setLocale(\Iyzipay\Model\Locale::TR);
            $request->setConversationId($unique_conversation_id);
            $request->setBinNumber(substr($card_number,0,6));
            $request->setPrice($total_amount);
    
            $installment_info = \Iyzipay\Model\InstallmentInfo::retrieve($request, $options)->getRawResult();
            $installment_info = json_decode($installment_info, true);
            $installment_index = array_search($installment_number, array_column($installment_info['installmentDetails'][0]['installmentPrices'], 'installmentNumber'));
            $total_with_installment = $installment_info['installmentDetails'][0]['installmentPrices'][$installment_index]['totalPrice'];
        }
        $request = new \Iyzipay\Request\CreatePaymentRequest();
        $request->setLocale($locale);
        $request->setConversationId($unique_conversation_id);
        $request->setPrice($cart_total_amount);
        $request->setPaidPrice($total_with_installment ? $total_with_installment : $cart_total_amount);
        $request->setCurrency(\Iyzipay\Model\Currency::TL);
        $request->setInstallment($installment_number);
        $request->setBasketId($order_info['order_id']);
        $request->setPaymentChannel(\Iyzipay\Model\PaymentChannel::WEB);
        $request->setPaymentGroup(\Iyzipay\Model\PaymentGroup::PRODUCT);

        $paymentCard = new \Iyzipay\Model\PaymentCard();
        $paymentCard->setCardHolderName($data['holderName']);
        $paymentCard->setCardNumber($card_number);
        $paymentCard->setExpireMonth($data['expireMonth']);
        $paymentCard->setExpireYear($data['expireYear']);
        $paymentCard->setCvc($cvc);
        $paymentCard->setRegisterCard(0);
        $request->setPaymentCard($paymentCard);
        $buyer = new \Iyzipay\Model\Buyer();
        $buyer->setId($order_customer_id);
        $buyer->setName($order_info_firstname);
        $buyer->setSurname($order_info_lastname);
        $buyer->setGsmNumber($order_info_telephone);
        $buyer->setEmail($order_info_email);
        $buyer->setIdentityNumber($customer_identity_number);
        //$buyer->setLastLoginDate("2015-10-05 12:43:35");
        if ($order_info['customer_id'] > 0) {
            $customer_query = $this->db->query("SELECT * FROM ps_customer WHERE customer_id = '" . (int) $order_info['customer_id'] . "' AND status = '1'");
            $added_date = !empty($customer_query->row['date_added']) ? $customer_query->row['date_added'] : "NOT PROVIDED";
            $buyer->setRegistrationDate($added_date);
        }
        $buyer->setRegistrationAddress($customer_address);
        $buyer->setIp($order_info_ip);
        $buyer->setCity($order_info_payment_zone);
        $buyer->setCountry($order_info_payment_country);
        $buyer->setZipCode($order_info_payment_postcode);
        $request->setBuyer($buyer);
        $shipping_address = new \Iyzipay\Model\Address();
        $shipping_address->setContactName($shipping_name);
        $shipping_address->setCity($shipping_city);
        $shipping_address->setCountry($shipping_country);
        $shipping_address->setAddress($customer_shipping_address);
        $shipping_address->setZipCode($shipping_zip_code);
        $request->setShippingAddress($shipping_address);
        $billing_address = new \Iyzipay\Model\Address();
        $billing_address->setContactName($order_info_firstname);
        $billing_address->setCity($order_info_payment_zone);
        $billing_address->setCountry($order_info_payment_country);
        $billing_address->setAddress($customer_address);
        $billing_address->setZipCode($order_info_payment_postcode);
        $request->setBillingAddress($billing_address);        
        $item = new \Iyzipay\Model\BasketItem();
        $item->setId(implode(',', $product_id));
        $item->setPrice($cart_total_amount);
        $item->setName($product_name);
        $item->setCategory1('NOT PROVIDED');
        $item->setItemType(\Iyzipay\Model\BasketItemType::PHYSICAL);
        $items[]= $item;
        $request->setBasketItems($items);
        
        # 3d'yi kontrol et veya DEBIT_CARD ise 3d kullan
        if((!empty($data['force3ds']) && $data['force3ds'] == 1) 
            || !empty($data['cardType']) && $data['cardType']=='DEBIT_CARD') {

            $request->setCallbackUrl("https://www.deercase.com/index.php?route=checkout/odeme/iyzicoCallback");

            $create_payment = \Iyzipay\Model\ThreedsInitialize::create($request, $options);
            $payment = json_decode($create_payment->getRawResult(), true);
            # Durum başarılı ve 3d sayfası göndermişse henüz para çekilmedi. 
            # 3D Sayfasını cevap olarak gönder.
            if($payment['status'] == "success") {
                $payment['threeDSHtmlContent'] = $create_payment->getHtmlContent();
            }        

            $safe_response = $this->getSafeResponse($payment);

            $payment = json_encode($safe_response, true);
        } else {            
            $create_payment = \Iyzipay\Model\Payment::create($request, $options);
            $payment = json_decode($create_payment->getRawResult(), true);
            $this->load->language('extension/payment/iyzico_checkout_form');
            $this->load->model('extension/payment/iyzico_checkout_form');

            # 3D Sayfasını göndermemiş ve durum başarılı ise para çekilmiştir.
            if($payment["status"] == "success" && empty($payment['threeDSHtmlContent'])) {
                
                # Siparişe yapılan ödemeyi kaydet.
                $message = "Payment ID: " . $payment["paymentId"];
                $this->model_checkout_order->addOrderHistory($order_info['order_id'], $this->config->get('iyzico_checkout_form_order_status_id'), $message, false);

                # Taksit Farkını Total'e ekle ve sipariş geçmişine not et.
                if($installment_number>1) {
                    $this->handleInstallmentAmount($create_payment, $order_info);
                }
            }

            $safe_response = $this->getSafeResponse($payment);
            $payment = json_encode($safe_response, true);    
        }

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

    public function installments() {
        $this->load->model('checkout/order');
        
        //$order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);
        $totals = $this->getCartTotals();
        foreach ($totals as $total) {
            if($total['code']=='total'){
                $total_amount = $total['value'];
            }
        }

        if($total_amount == 0) {
            die();
        }

        IyzipayBootstrap::init();

        $options = $this->getIyzicoOptions();
        $data = $this->request->get;
        $unique_conversation_id = uniqid($this->order_prefix) . "_" . $data['order_id'];

        $request = new \Iyzipay\Request\RetrieveInstallmentInfoRequest();
        $request->setLocale(\Iyzipay\Model\Locale::TR);
        $request->setConversationId($unique_conversation_id);
        $request->setBinNumber($data['number']);
        $request->setPrice($total_amount);

        $installment_info = \Iyzipay\Model\InstallmentInfo::retrieve($request, $options)->getRawResult();
        $installment_info = json_decode($installment_info, true);
        
        for($i=0;$i<count($installment_info['installmentDetails'][0]['installmentPrices']);$i++) {
            $installment_info['installmentDetails'][0]['installmentPrices'][$i]['installmentPrice'] = $this->currency->format($installment_info['installmentDetails'][0]['installmentPrices'][$i]['installmentPrice'], $this->session->data['currency']);
            $installment_info['installmentDetails'][0]['installmentPrices'][$i]['totalPrice'] = $this->currency->format($installment_info['installmentDetails'][0]['installmentPrices'][$i]['totalPrice'], $this->session->data['currency']);
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($installment_info['installmentDetails'][0]));
    }

    public function iyzicoCallback() {
        $options = $this->getIyzicoOptions();

        $data = array_merge($_POST, (array) json_decode(file_get_contents('php://input')));
        
        if($data['conversationId'] == $this->session->data['conversation_id']) {
            if($data['mdStatus'] == 1) {
                $request = new \Iyzipay\Request\CreateThreedsPaymentRequest();
                $request->setLocale(\Iyzipay\Model\Locale::TR);
                $request->setConversationId($data['conversationId']);
                $request->setPaymentId($data['paymentId']);
                $request->setConversationData($data['conversationData']);

                # make request
                $threeds_payment = \Iyzipay\Model\ThreedsPayment::create($request, $options);
                $threeds_payment_raw = json_decode($threeds_payment->getRawResult(), true);

                $this->load->model('checkout/order');
                $order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);

                if($threeds_payment_raw['status']=='success') {
                     # Siparişe yapılan ödemeyi kaydet.
                    $message = "Payment ID: " . $data["paymentId"];
                    $this->model_checkout_order->addOrderHistory($order_info['order_id'], $this->config->get('iyzico_checkout_form_order_status_id'), $message, false);
                    # Taksit Farkını Total'e ekle ve sipariş geçmişine not et.
                    if($threeds_payment_raw['installment']>1) {
                        $this->handleInstallmentAmount($threeds_payment, $order_info);
                    }
                }          
            } else {
                if(in_array($data['mdStatus'], [0,2,3,4,5,6,7,8])) {
                    switch ($data['mdStatus']) {
                        case '0':
                            $this->session->data['3d_error'] = "3-D Secure imzası geçersiz veya doğrulama";
                            break;                   
                        case '2':
                            $this->session->data['3d_error'] = "Kart sahibi veya bankası sisteme kayıtlı değil";
                            break;                    
                        case '3':
                            $this->session->data['3d_error'] = "Kartın bankası sisteme kayıtlı değil";
                            break;                   
                        case '4':
                            $this->session->data['3d_error'] = "Doğrulama denemesi, kart sahibi sisteme daha sonra kayıt olmayı seçmiş";
                            break;                   
                        case '5':
                            $this->session->data['3d_error'] = "Doğrulama yapılamıyor";                   
                        case '6':
                            $this->session->data['3d_error'] = "3-D Secure hatası";
                            break;
                        case '7':
                            $this->session->data['3d_error'] = "Sistem hatası";
                            break;
                        case '8':
                            $this->session->data['3d_error'] = "Bilinmeyen kart no";
                            break;
                    }
                    header("Location: https://www.deercase.com/odeme2/#/payment");

                }

            }
        }

    }

    private function getCartTotals() {
       $this->load->model('extension/extension');

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

       // Because __call can not keep var references so we put them into an array.
       $total_data = array(
           'totals' => &$totals,
           'taxes' => &$taxes,
           'total' => &$total
       );

       if ($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);
               }
           }

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

           array_multisort($sort_order, SORT_ASC, $totals);

           return $totals;
       }
    }

    public function checkThreedErrors() {
        if(!empty($this->session->data['3d_error'])) {
            $data = 'Ödeme Başarısız: ' . $this->session->data['3d_error'];
            unset($this->session->data['3d_error']);
            $this->response->addHeader('Content-Type: application/json');
            $this->response->setOutput(json_encode(['message' => $data]));
        }
    }
    private function getIyzicoOptions() {
        IyzipayBootstrap::init();

        // $merchant_api_id = $this->config->get('iyzico_checkout_form_api_id_live');
        // $merchant_secret_key = $this->config->get('iyzico_checkout_form_secret_key_live');        
    
        $merchant_api_id = "sandbox-zUItlePToEDwu5WKqbZUbvC6Vd1h8ugn";
        $merchant_secret_key = "sandbox-DJXmt88OUbTWTBvJkuRCPK7ou2Zkpjau";
        
        $options = new \Iyzipay\Options();
        $options->setApiKey($merchant_api_id);
        $options->setSecretKey($merchant_secret_key);
        $options->setBaseUrl($this->base_url);

        return $options;
    }

    private function getSafeResponse($payment) {
        $safe_response = [
            'status' => $payment['status'],
        ];        
        
        if(!empty($payment['threeDSHtmlContent'])) {
            $safe_response['threeDSHtmlContent'] = $payment['threeDSHtmlContent'];
        }    
               
        if(!empty($payment['errorMessage'])) {
            $safe_response['errorMessage'] = $payment['errorMessage'];
        }   

        return $safe_response;
    }

    private function handleInstallmentAmount($response, $order_info) {
        $order_id = $order_info['order_id'];
        $this->load->model('checkout/order');
        $order_total = (array) $this->db->query("SELECT * FROM " . DB_PREFIX ."order_total WHERE order_id = '" . (int) $order_id . "' AND code = 'total' ");
        $last_sort_value = $order_total['row']['sort_order'] - 1;
        $exchange_rate = $this->currency->getValue($order_info['currency_code']);
        $new_amount = str_replace(',', '', $response->getPaidPrice());
        $old_amount = str_replace(',', '', $order_info['total'] * $order_info['currency_value']);
        $installment_fee_variation = ($new_amount - $old_amount) / $exchange_rate;
        $this->db->query("INSERT INTO " . DB_PREFIX ."order_total SET order_id = '" .
            (int) $order_id . "',code = '" . $this->db->escape('iyzico_checkout_form_fee') .
            "',  title = '" . $this->db->escape($this->language->get('installment_charge')) . "' , `value` = '" .
            (float) $installment_fee_variation . "', sort_order = '" . (int) $last_sort_value . "'");
        $order_total_data = (array) $this->db->query("SELECT * FROM " . DB_PREFIX ."order_total 
                    WHERE order_id = '" . (int) $order_id . "' 
                    AND code != 'total'
                    AND code != 'coupon'
                    AND code != 'campaign_price_total' ");
        $calculate_total = 0;
        foreach ($order_total_data['rows'] as $row) {
            $calculate_total += $row['value'];
        }
        $this->db->query("UPDATE " . DB_PREFIX ."order_total SET  `value` = '" . (float) $calculate_total . "' WHERE order_id = '$order_id' AND code = 'total' ");
        $this->db->query("UPDATE " . DB_PREFIX ."order SET total = '" . $calculate_total . "' WHERE order_id = '" . (int) $order_id . "'");
        $comment = $response->getCardFamily() . ' - ' . $response->getInstallment() . '  Taksit';
        $this->db->query("INSERT INTO " . DB_PREFIX ."order_history SET order_id = '" . (int) $order_id . "', order_status_id = '" .
        $this->config->get('iyzico_checkout_form_order_status_id') . "', notify = '0', comment = '" .
        $this->db->escape($comment) . "', date_added = NOW()");
    }
}