<?php
class ControllerPaymentPayu extends Controller {
 	private $error = array();

	public function index() {
		$this->load->language('payment/payu');

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

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

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

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

    $this->document->addScript(array(
        'public/js/payment/payu.js'
    ));


		if (($this->request->server['REQUEST_METHOD'] == 'POST') && ($this->validate())) {
			$this->model_setting_setting->editSetting('payu', $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'));
		}


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

		$this->data['entry_callback'] = $this->language->get('entry_callback');
    $this->data['link_callback']  = $this->urlloja->link('payment/payu/callback');
    $this->data['entry_success']  = $this->language->get('entry_success');
    $this->data['link_successs']  = $this->urlloja->link('payment/payu/callback');
    $this->data['url_validate_credentials'] = $this->url->link('payment/payu/validateCredentials', 'token=' . $this->session->data['token'], 'SSL');

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

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

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

		if (isset($this->error['merchantId'])) {
		  $this->data['error_merchantId'] = $this->error['merchantId'];
		} else {
		  $this->data['error_merchantId'] = '';
		}
		if (isset($this->error['accountId'])) {
		  $this->data['error_accountId'] = $this->error['accountId'];
		} else {
		  $this->data['error_accountId'] = '';
		}
		if (isset($this->error['apilogin'])) {
		  $this->data['error_apilogin'] = $this->error['apilogin'];
		} else {
		  $this->data['error_apilogin'] = '';
		}
		if (isset($this->error['apikey'])) {
		  $this->data['error_apikey'] = $this->error['apikey'];
		} else {
		  $this->data['error_apikey'] = '';
		}

		$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/payu', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL'),
				'text'      => $this->language->get('heading_title'),
				'separator' => ' :: '
		);

		$this->data['action'] = $this->url->link('payment/payu', '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');

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

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

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

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

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

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

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

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


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

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

		if (isset($this->request->post['payu_order_aprovado'])) {
		  $this->data['payu_order_aprovado'] = $this->request->post['payu_order_aprovado'];
		} else {
		  $this->data['payu_order_aprovado'] = $this->config->get('payu_order_aprovado');
		}
		if (isset($this->request->post['payu_order_pendente'])) {
		  $this->data['payu_order_pendente'] = $this->request->post['payu_order_pendente'];
		} else {
		  $this->data['payu_order_pendente'] = $this->config->get('payu_order_pendente');
		}
		if (isset($this->request->post['payu_order_rejeitado'])) {
		  $this->data['payu_order_rejeitado'] = $this->request->post['payu_order_rejeitado'];
		} else {
		  $this->data['payu_order_rejeitado'] = $this->config->get('payu_order_rejeitado');
		}
		if (isset($this->request->post['payu_order_erro'])) {
		  $this->data['payu_order_erro'] = $this->request->post['payu_order_erro'];
		} else {
		  $this->data['payu_order_erro'] = $this->config->get('payu_order_erro');
		}
		if (isset($this->request->post['payu_order_expirado'])) {
		  $this->data['payu_order_expirado'] = $this->request->post['payu_order_expirado'];
		} else {
		  $this->data['payu_order_expirado'] = $this->config->get('payu_order_expirado');
		}

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

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

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

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

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

		$this->data['geo_zones'] = $this->model_localisation_geo_zone->getGeoZones();

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

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

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

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

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

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

	private function validate() {

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

		if (utf8_strlen($this->request->post['payu_title'])>40) {
		  $this->error['title'] = $this->language->get('error_title');
		}

		if ((!$this->request->post['payu_merchantId'])&&((utf8_strlen($this->request->post['payu_merchantId'])>12)||(utf8_strlen($this->request->post['payu_merchantId'])<1))) {
		    $this->error['merchantId'] = $this->language->get('error_merchantId');
		}

		if ((!$this->request->post['payu_accountId'])&&((utf8_strlen($this->request->post['payu_accountId'])>6)||(utf8_strlen($this->request->post['payu_accountId'])<1))) {
			$this->error['accountId'] = $this->language->get('error_accountId');
		}

		if ((!$this->request->post['payu_apilogin'])&&(utf8_strlen($this->request->post['payu_apilogin'])<1)) {
			$this->error['apilogin'] = $this->language->get('error_apilogin');
		}

		if ((!$this->request->post['payu_apikey'])&&(utf8_strlen($this->request->post['payu_apikey'])<1)) {
			$this->error['apikey'] = $this->language->get('error_apikey');
		}

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

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

        $login = $this->request->get['payu_apilogin'];
        $key = $this->request->get['payu_apikey'];
        $merchant = (object) ['apiLogin' => $login, 'apiKey' => $key];

        $requestApi = new RestApi;

        try {
            $dataSend = ['test' => 'false', 'language' => 'en', 'command' => 'PING', 'merchant' => $merchant];
            $header =  array('Content-Type: application/json', 'Accept: application/json');
            $url = 'https://sandbox.api.payulatam.com/reports-api/4.0/service.cgi';
            $result = (Array) $requestApi->callAPI($url, 'POST', $dataSend, $header, false, $retorno,Type_DadosSend::TpDados_Json);
        } catch (Exception $e) {
            $result['error'] = $e;
        }

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