<?php
class ControllerExtensionPaymentSanalpos extends Controller
{
    public function index()
    {

        foreach ($this->load->language('extension/payment/sanalpos') as $l_key => $lang) {
            $data[$l_key] = $lang;
        }

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

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

    }

    public function cartcontrol()
    {
        $this->load->language('extension/payment/sanalpos');
        $this->load->model('extension/payment/sanalpos');

        $json = array();
        if (isset($this->request->post['card_number']) and $this->request->post['card_number']) {
            $card_number = $this->request->post['card_number'];
            if (is_numeric($card_number)) {
                if (strlen($card_number) == 6 OR strlen($card_number) == 16) {
                    $card_number = substr($card_number, 0, 6); 
                    $bank_info = $this->model_extension_payment_sanalpos->getBank($card_number); 
                    if (isset($bank_info['banka_adi'])) {
                        $json['message'] = $bank_info['banka_adi'];
                        $this->session->data['sanalpos_bankid'] = $bank_info['bank_id'];
                        $this->session->data['sanalpos_cart_type'] = $bank_info['cart_type'];
                        $json['cart_type'] = 0; 
                        if ($this->config->get($bank_info['path'] . '_sanalpos_status')) { 
                            $json['cart_type'] = $this->session->data['sanalpos_cart_type']; 
                            $json['instalments'] = $this->model_extension_payment_sanalpos->calcInstalment($this->config->get($bank_info['path'] . '_sanalpos_taksit_rate'));
                        }else{
                            $json['cart_type'] = $this->session->data['sanalpos_cart_type'];
                            $default_rate = explode('-', $this->config->get('sanalpos_default_bank_taksit_rate'));
                            //$default_rate = explode(':', $default_rate[0]);
                            $json['instalments'] = $this->model_extension_payment_sanalpos->calcInstalment($default_rate[0]);
                        } 
                    } else {
                        $json['message'] = "Yanlış kart numarası girdiniz";
                        $this->session->data['sanalpos_bankid'] = 0;
                    }

                } else {
                    //$json['error']= $this->language->get('error_cart_number_limit');
                }
            } else {
                $json['error'] = $this->language->get('error_cart_not_numeric');
            }
        }

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

    public function pay()
    {
        $this->load->model('extension/payment/sanalpos');

        $json = array();
        if (isset($this->request->post)) {

            $error = $this->cartFieldControl($this->request->post);
            if (!$error) {
                $bank_info = $this->model_extension_payment_sanalpos->getBankByBankId($this->session->data['sanalpos_bankid']);
                if ($this->config->get($bank_info['path'] . '_status')) {

                } else if ($this->config->get('sanalpos_default_bank')) { 
                    $this->load->model('extension/payment/banks/' . $this->config->get('sanalpos_default_bank'));
                    $json = $this->{'model_extension_payment_banks_' . $this->config->get('sanalpos_default_bank')}->letPay($this->request->post);
                    
                } else {
                    $json['error'] = "Yöneticiyle görüşün!";
                }
            } else {
                $json['error'] = $error;
            }

        }

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

    protected function cartFieldControl($data)
    {
        $error = '';
        if (empty($data['card_number']) or !isset($data['card_number'])) {
            $error = 'Kart numarası yazmalısınız!';
        } else {
            if (strlen($data['card_number']) != 16) {
                $error = 'Kart numarası 16 haneli olmalıdır!';
            }
        }

        if (empty($data['last_use_date'])) {
            $error = 'Kartın son kullanım tarihini yazmalısınız!';
        } else {
            if (strlen($data['last_use_date']) != 4) {
                $error = 'Kartın son kullanım tarihini MMYY şeklinde yazmalısınız!';
            }
            if (!is_numeric($data['last_use_date'])) {
                $error = 'Kartın son kullanım tarihini yanlış girdiniz.';
            }
        }

        if (empty($data['cv_code'])) {
            $error = 'Kartın arkasındaki güvenlik kodunu yazmalısınız!';
        } else {
            if (!is_numeric($data['cv_code'])) {
                $error = 'Kartın arkasındaki güvenlik kodunu yanlış girdiniz.';
            }
        }

        if (empty($data['member_name'])) {
            $error = 'Kartın üzerindeki İsim Soyisimi yazınız!';
        }

        return $error;

    }

    public function callback()
    {   
 
        if (isset($this->request->get['pos']) and isset($this->request->get['page'])) {
            $pos = $this->request->get['pos'];
            $page = $this->request->get['page'];
            if ($pos == 'turkiyefinans') {
                $data = $this->turkiyefinans($this->request->post, $page);
                if (isset($data['success']) and $data['success']) {
                    $this->response->redirect($this->url->link('checkout/success', '', true));
                }
            }else if($pos == 'garanti'){ 
                $data = $this->garanti($this->request->post, $page);
                if (isset($data['success']) and $data['success']) {
                    $this->response->redirect($this->url->link('checkout/success', '', true));
                }
            }
        } else {
            $this->response->redirect($this->url->link('error/not_found'));
        }


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

    }

    private function turkiyefinans($post_data, $page)
    {

        $this->load->model('extension/payment/sanalpos');
        $data = array();
        if ($page == 'ok') {
            $this->load->model('checkout/order');
            if ($post_data) {
                $log = new Log("Turkiyefinans_Ok_Log.txt");
                $log->write($post_data);
                if (in_array($post_data['mdStatus'], array(1, 2, 3, 4))) {
                    $this->model_extension_payment_sanalpos->returnOk($post_data);
                    if ($post_data['Response'] == 'Approved') {
                        $data['message_type'] = 'error';
                        $data['message'] = $post_data['ErrMsg'];
                        $data['checkout'] = $this->url->link('checkout/checkout', '', true);

                        $data['success'] = true;
                        if(empty($post_data['taksit'])){
                            $post_data['taksit'] = 'Tek Çekim';
                        }else{
                            $post_data['taksit'] = $post_data['taksit'] . ' Taksit';
                        }
                        $comment = '';
                        $comment .= '';
                        $comment .= 'Türkiyefinans Sanal Pos - ' . $post_data['taksit'] . ' ' . $post_data['EXTRA_CARDISSUER'];
                        $this->model_checkout_order->addOrderHistory($this->session->data['order_id'], $this->config->get('sanalpos_order_completed_id'), $comment, true);

                    } else {

                    }
                }
            }

        } else if ($page == 'fail') {
            if ($post_data) {
                $log = new Log("Turkiyefinans_Fail_Log.txt");
                $log->write($post_data);
                if (in_array($post_data['mdStatus'], array(1, 2, 3, 4))) {
                    $this->model_extension_payment_sanalpos->returnFail($post_data);
                    $data['message_type'] = 'error';
                    $data['message'] = $post_data['ErrMsg'];
                    $data['checkout'] = $this->url->link('checkout/checkout', '', true);

                } else if ($post_data['mdStatus'] == 0) {
                    $data['message_type'] = 'error';
                    $data['message'] = '3D işlemi başarısız!';
                    $data['checkout'] = $this->url->link('checkout/checkout', '', true);
                } else {
                    $this->response->redirect($this->url->link('error/not_found'));
                }
            }
        } else {
            $this->response->redirect($this->url->link('error/not_found'));
        }

        return $data;

    }

    private function garanti($post_data, $page)
    {
       
        
        $this->load->model('extension/payment/sanalpos');
        $data = array();
        if ($page == 'ok') {
            $this->load->model('checkout/order');
            if ($post_data OR 1 == 1) {
                
                //if (in_array($post_data['mdStatus'], array(1, 2, 3, 4))) {
                    //$this->model_extension_payment_sanalpos->returnOk($post_data);
                   // if ($post_data['Response'] == 'Approved') {
                        $data['message_type'] = 'error';
                        $data['message'] = 'İşlem Başarılı';
                        $data['checkout'] = $this->url->link('checkout/checkout', '', true);

                        $data['success'] = true;
                       
                        $comment = '';
                        $comment .= '';
                        $comment .= 'Garanti Sanal Pos ';
                        $this->model_checkout_order->addOrderHistory($this->session->data['order_id'], $this->config->get('sanalpos_order_completed_id'), $comment, true);

                   // } 
                //}
            }

        } else if ($page == 'fail') {
            $data['message_type'] = 'error';
            $data['message'] = 'İlem Başarısız';
            $data['checkout'] = $this->url->link('checkout/checkout', '', true);
        } else {
            $this->response->redirect($this->url->link('error/not_found'));
        }

        return $data;

    }




}
