<?php

class ControllerPaymentMercadopago2 extends Controller
{
    private $error = array();

    public function index()
    {

        $this->load->type('tipocomum');

        $language = $this->load->language('payment/mercadopago2');
        $this->data = array_merge($this->data, $language);

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

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

        $this->document->addScript(array(
            'view/javascript/payment-mercadopago.js'
        ));

        $this->data['Type_DisplayModuleOption'] = $this->load->typeForTwig('Type_DisplayModuleOption');

        $this->data['ftr_geral'] = new ftr_geral();

        if (($this->request->server['REQUEST_METHOD'] == 'POST') && ($this->validate())) {
            $this->removeMasks();

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

            if (isset($this->request->post['mercadopago2_methods'])) {
                $names = $this->request->post['mercadopago2_methods'];
                $this->request->post['mercadopago2_methods'] = '';
                foreach ($names as $name) {
                    $this->request->post['mercadopago2_methods'] .= $name . ',';
                }
            }

            $this->model_setting_setting->editSetting('mercadopago2', $this->request->post);
            $this->session->data['success'] = $this->language->get('text_success');
            $this->redirect($this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL'));
        }

        $this->data['ipn_obs_link'] = $this->urlloja->link('payment/mercadopago2/retorno/&');
        $this->data['text_welcome'] = sprintf($this->language->get('text_welcome'), $this->url->link('account/login', '', 'SSL'), $this->url->link('account/register', '', 'SSL'));

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

        $this->data['breadcrumbs'][] = array(
            'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
            'text' => $this->language->get('text_home'),
            'separator' => FALSE
        );

        $this->data['breadcrumbs'][] = array(
            'href' => $this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL'),
            'text' => $this->language->get('text_payment'),
            'separator' => ' :: '
        );

        $this->data['breadcrumbs'][] = array(
            'href' => $this->url->link('payment/mercadopago2', 'token=' . $this->session->data['token'], 'SSL'),
            'text' => $this->language->get('heading_title'),
            'separator' => ' :: '
        );

        if (isset($this->error['warning'])) {
            $this->data['error_warning'] = $this->error['warning'];
        } else {
            $this->data['error_warning'] = '';
        }

        if (isset($this->error['acc_id'])) {
            $this->data['error_acc_id'] = $this->error['acc_id'];
        } else {
            $this->data['error_acc_id'] = '';
        }

        if (isset($this->error['token'])) {
            $this->data['error_token'] = $this->error['token'];
        } else {
            $this->data['error_token'] = '';
        }

        $this->data['action'] = $this->url->link('payment/mercadopago2', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL');

        $this->data['cancel'] = $this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL');
        //$this->config->get('config_adm_ssl') . 'index.php?route=extension/module&token=' . $this->session->data['token'] . '&module=' . $this->request->get['type'];
        $this->data['url_validate_credentials'] = $this->url->link('payment/mercadopago2/validateCredentials', 'token=' . $this->session->data['token'], 'SSL');

        if (isset($this->request->post['mercadopago2_title'])) {
            $this->data['mercadopago2_title'] = $this->request->post['mercadopago2_title'];
        } else {
            $this->data['mercadopago2_title'] = $this->config->get('mercadopago2_title');
        }

        if (isset($this->request->post['mercadopago2_client_id'])) {
            $this->data['mercadopago2_client_id'] = $this->request->post['mercadopago2_client_id'];
        } else {
            $this->data['mercadopago2_client_id'] = $this->config->get('mercadopago2_client_id');
        }

        if (isset($this->request->post['mercadopago2_email'])) {
            $this->data['mercadopago2_email'] = $this->request->post['mercadopago2_email'];
        } else {
            $this->data['mercadopago2_email'] = $this->config->get('mercadopago2_email');
        }

        if (isset($this->request->post['mercadopago2_user_email'])) {
            $this->data['mercadopago2_user_email'] = $this->request->post['mercadopago2_user_email'];
        } else {
            $this->data['mercadopago2_user_email'] = $this->config->get('mercadopago2_user_email');
        }

        if (isset($this->request->post['mercadopago2_valor_minimo'])) {
            $this->data['mercadopago2_valor_minimo'] = $this->request->post['mercadopago2_valor_minimo'];
        } else if ($this->config->get('mercadopago2_valor_minimo')) {
            $this->data['mercadopago2_valor_minimo'] = $this->config->get('mercadopago2_valor_minimo');
        } else {
            $this->data['mercadopago2_valor_minimo'] = 0;
        }

        if (isset($this->request->post['mercadopago2_parcela_minima'])) {
            $this->data['mercadopago2_parcela_minima'] = $this->request->post['mercadopago2_parcela_minima'];
        } else {
            $this->data['mercadopago2_parcela_minima'] = $this->config->get('mercadopago2_parcela_minima');
        }

        if (isset($this->request->post['mercadopago2_client_secret'])) {
            $this->data['mercadopago2_client_secret'] = $this->request->post['mercadopago2_client_secret'];
        } else {
            $this->data['mercadopago2_client_secret'] = $this->config->get('mercadopago2_client_secret');
        }

        if (isset($this->request->post['mercadopago2_status'])) {
            $this->data['mercadopago2_status'] = $this->request->post['mercadopago2_status'];
        } else {
            $this->data['mercadopago2_status'] = $this->config->get('mercadopago2_status');
        }


        $this->data['category_list'] = $this->getCategoryList();
        if (isset($this->request->post['mercadopago2_category_id'])) {
            $this->data['mercadopago2_category_id'] = $this->request->post['mercadopago2_category_id'];
        } else {
            $this->data['mercadopago2_category_id'] = $this->config->get('mercadopago2_category_id');
        }


        if (isset($this->request->post['mercadopago2_url'])) {
            $this->data['mercadopago2_url'] = $this->request->post['mercadopago2_url'];
        } else {
            $this->data['mercadopago2_url'] = $this->config->get('mercadopago2_url');
        }

        if (isset($this->request->post['mercadopago2_debug'])) {
            $this->data['mercadopago2_debug'] = $this->request->post['mercadopago2_debug'];
        } else {
            $this->data['mercadopago2_debug'] = $this->config->get('mercadopago2_debug');
        }


        if (isset($this->request->post['mercadopago2_sandbox'])) {
            $this->data['mercadopago2_sandbox'] = $this->request->post['mercadopago2_sandbox'];
        } else {
            $this->data['mercadopago2_sandbox'] = $this->config->get('mercadopago2_sandbox');
        }


        if (isset($this->request->post['mercadopago2_display'])) {
            $this->data['mercadopago2_display'] = $this->request->post['mercadopago2_display'];
        } else {
            $this->data['mercadopago2_display'] = $this->config->get('mercadopago2_display');
        }

        $this->data['countries'] = $this->getCountries();
        $this->data['installments'] = $this->getInstallments();
        $this->data['methods'] = $this->getMethods(Type_CountryMercadoPago::getNickFromValue(Type_CountryMercadoPago::Tp_Brasil));


        if (isset($this->request->post['mercadopago2_methods'])) {
            $this->data['mercadopago2_methods'] = $this->request->post['mercadopago2_methods'];
        } else {
            $methods_excludes = preg_split("/[\s,]+/", $this->config->get('mercadopago2_methods'));
            foreach ($methods_excludes as $exclude) {
                $this->data['mercadopago2_methods'][] = $exclude;
            }
        }

        if (isset($this->request->post['mercadopago2_methods_value'])) {
            $this->data['mercadopago2_methods_value'] = $this->request->post['mercadopago2_methods_value'];
        } else {
            $this->data['mercadopago2_methods_value'] = $this->config->get('mercadopago2_methods_value');
        }


        if (isset($this->request->post['mercadopago2_installments'])) {
            $this->data['mercadopago2_installments'] = $this->request->post['mercadopago2_installments'];
        } else {
            $this->data['mercadopago2_installments'] = $this->config->get('mercadopago2_installments');
        }

        if (isset($this->request->post['mercadopago2_order_status_id'])) {
            $this->data['mercadopago2_order_status_id'] = $this->request->post['mercadopago2_order_status_id'];
        } else {
            $this->data['mercadopago2_order_status_id'] = $this->config->get('mercadopago2_order_status_id');
        }

        if (isset($this->request->post['mercadopago2_sort_order'])) {
            $this->data['mercadopago2_sort_order'] = $this->request->post['mercadopago2_sort_order'];
        } else {
            $this->data['mercadopago2_sort_order'] = $this->config->get('mercadopago2_sort_order');
        }
        if (isset($this->request->post['mercadopago2_order_status_id_completed'])) {
            $this->data['mercadopago2_order_status_id_completed'] = $this->request->post['mercadopago2_order_status_id_completed'];
        } else {
            $this->data['mercadopago2_order_status_id_completed'] = $this->config->get('mercadopago2_order_status_id_completed');
        }

        if (isset($this->request->post['mercadopago2_order_status_id_pending'])) {
            $this->data['mercadopago2_order_status_id_pending'] = $this->request->post['mercadopago2_order_status_id_pending'];
        } else {
            $this->data['mercadopago2_order_status_id_pending'] = $this->config->get('mercadopago2_order_status_id_pending');
        }

        if (isset($this->request->post['mercadopago2_order_status_id_canceled'])) {
            $this->data['mercadopago2_order_status_id_canceled'] = $this->request->post['mercadopago2_order_status_id_canceled'];
        } else {
            $this->data['mercadopago2_order_status_id_canceled'] = $this->config->get('mercadopago2_order_status_id_canceled');
        }

        if (isset($this->request->post['mercadopago2_order_status_id_in_process'])) {
            $this->data['mercadopago2_order_status_id_in_process'] = $this->request->post['mercadopago2_order_status_id_in_process'];
        } else {
            $this->data['mercadopago2_order_status_id_in_process'] = $this->config->get('mercadopago2_order_status_id_in_process');
        }

        if (isset($this->request->post['mercadopago2_order_status_id_rejected'])) {
            $this->data['mercadopago2_order_status_id_rejected'] = $this->request->post['mercadopago2_order_status_id_rejected'];
        } else {
            $this->data['mercadopago2_order_status_id_rejected'] = $this->config->get('mercadopago2_order_status_id_rejected');
        }

        if (isset($this->request->post['mercadopago2_order_status_id_refunded'])) {
            $this->data['mercadopago2_order_status_id_refunded'] = $this->request->post['mercadopago2_order_status_id_refunded'];
        } else {
            $this->data['mercadopago2_order_status_id_refunded'] = $this->config->get('mercadopago2_order_status_id_refunded');
        }

        if (isset($this->request->post['mercadopago2_order_status_id_in_mediation'])) {
            $this->data['mercadopago2_order_status_id_in_mediation'] = $this->request->post['mercadopago2_order_status_id_in_mediation'];
        } else {
            $this->data['mercadopago2_order_status_id_in_mediation'] = $this->config->get('mercadopago2_order_status_id_in_mediation');
        }

        if (isset($this->error['error_client_id'])) {
            $this->data['error_client_id'] = $this->error['error_client_id'];
        } else {
            $this->data['error_client_id'] = '';
        }

        if (isset($this->error['error_mercadopago2_email'])) {
            $this->data['error_mercadopago2_email'] = $this->error['error_mercadopago2_email'];
        } else {
            $this->data['error_mercadopago2_email'] = '';
        }

        if (isset($this->error['error_mercadopago2_user_email'])) {
            $this->data['error_mercadopago2_user_email'] = $this->error['error_mercadopago2_user_email'];
        } else {
            $this->data['error_mercadopago2_user_email'] = '';
        }

        if (isset($this->error['error_client_secret'])) {
            $this->data['error_client_secret'] = $this->error['error_client_secret'];
        } else {
            $this->data['error_client_secret'] = '';
        }

        if (isset($this->error['error_mercadopago2_url'])) {
            $this->data['error_mercadopago2_url'] = $this->error['error_mercadopago2_url'];
        } else {
            $this->data['error_mercadopago2_url'] = '';
        }


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

        $this->data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();

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

        $this->response->setOutput($this->render('payment/mercadopago2'));
    }

    protected function removeMasks(){
        if(isset($this->request->post['mercadopago2_valor_minimo']) && $this->request->post['mercadopago2_valor_minimo']){
            $this->request->post['mercadopago2_valor_minimo'] = ftr_geral::removeMaskToDouble($this->request->post['mercadopago2_valor_minimo']);
        }

        if(isset($this->request->post['mercadopago2_parcela_minima']) && $this->request->post['mercadopago2_parcela_minima']){
            $this->request->post['mercadopago2_parcela_minima'] = ftr_geral::removeMaskToDouble($this->request->post['mercadopago2_parcela_minima']);
        }

        if($this->request->post['mercadopago2_methods_value']){
            foreach ($this->request->post['mercadopago2_methods_value'] as $key => $value){
                $this->request->post['mercadopago2_methods_value'][$key] = ftr_geral::removeMaskToDouble($value);
            }
        }
    }

    private function getCountries()
    {
        $this->load->helper('ftr_geral');

        $url = 'https://api.mercadolibre.com/sites/';
        $countries = ftr_geral::callJson($url);

        return $countries;
    }

    private function getMethods($country_id)
    {
        $this->load->helper('ftr_geral');

        $url = "https://api.mercadolibre.com/sites/" . $country_id . "/payment_methods";
        $methods = ftr_geral::callJson($url);

        return $methods;
    }

    private function getCategoryList()
    {
        $this->load->helper('ftr_geral');

        $url = "https://api.mercadolibre.com/item_categories";
        $category = ftr_geral::callJson($url);

        return $category;
    }

    private function getInstallments()
    {

        $installments = array();

        $installments[] = array(
            'value' => '24',
            'id' => '24');

        $installments[] = array(
            'value' => '18',
            'id' => '18');
        $installments[] = array(
            'value' => '15',
            'id' => '15');

        $installments[] = array(
            'value' => '12',
            'id' => '12');

        $installments[] = array(
            'value' => '9',
            'id' => '9');

        $installments[] = array(
            'value' => '6',
            'id' => '6');

        $installments[] = array(
            'value' => '3',
            'id' => '3');

        $installments[] = array(
            'value' => '1',
            'id' => '1');

        return $installments;
    }


    private function validate()
    {
        if (!$this->user->hasPermission('modify', 'payment/mercadopago2')) {
            $this->error['warning'] = $this->language->get('error_permission');
        }

        if (!$this->request->post['mercadopago2_client_id']) {
            $this->error['error_client_id'] = $this->language->get('error_client_id');
        }

        if (!$this->request->post['mercadopago2_client_secret']) {
            $this->error['error_client_secret'] = $this->language->get('error_client_secret');
        }

        if (!$this->request->post['mercadopago2_url']) {
            $this->error['error_mercadopago2_url'] = $this->language->get('error_mercadopago2_url');
        }

        if ((utf8_strlen($this->request->post['mercadopago2_email']) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $this->request->post['mercadopago2_email']) || !filter_var($this->request->post['mercadopago2_email'], FILTER_VALIDATE_EMAIL) || !preg_match('/^[a-zA-Z0-9\._-]+@/', $this->request->post['mercadopago2_email'])) {
            $this->error['error_mercadopago2_email'] = $this->language->get('error_mercadopago2_email');
        }

        if ($this->request->post['mercadopago2_sandbox'] && $this->request->post['mercadopago2_sandbox'] == Type_Status::Tp_Habilitado) {
            if ((utf8_strlen($this->request->post['mercadopago2_user_email']) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $this->request->post['mercadopago2_email']) || !filter_var($this->request->post['mercadopago2_user_email'], FILTER_VALIDATE_EMAIL) || !preg_match('/^[a-zA-Z0-9\._-]+@/', $this->request->post['mercadopago2_user_email'])) {
                $this->error['error_mercadopago2_user_email'] = $this->language->get('error_mercadopago2_email');
            }
        }


        if (!$this->error) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    public function validateCredentials()
    {
        $this->load->language('payment/mercadopago2');

        MercadoPago\SDK::setClientId($this->request->get['mercadopago2_client_id']);
        MercadoPago\SDK::setClientSecret($this->request->get['mercadopago2_client_secret']);

        $access_token = MercadoPago\SDK::getAccessToken();

        if (!empty($access_token)) {
            $this->response->setOutputJson([
                'type' => 'success',
                'message' => $this->language->get('text_success_validate')
            ]);
        } else {
            $this->response->setOutputJson([
                'type' => 'error',
                'message' => $this->language->get('text_error_validate')
            ]);
        }
    }
}
