<?php
$loader = $this->registry->get('load');
$loader->controller('payment/geralconfigs');

use Moip\Moip;
use Moip\Auth\OAuth;
use Moip\Auth\BasicAuth;

class ControllerPaymentWirecard extends ControllerPaymentGeralConfigs
{

  private $error = array();
  private $moip = false;

  public function index()
  {
      parent::index();

      $this->load->model('setting/setting');
      $this->load->type('tipowirecard');
      $this->load->model('localisation/order_status');
      $this->load->model('setting/extension');
      $this->load->dmodel('tool/image');
      $this->loadMoip();

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

      $this->document->addScript(array(
        'view/javascript/page.payment_type.js',
        'view/javascript/page.wirecard.js'
      ));

      $this->data['cancel'] = $this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL');
      $this->data['action'] = $this->url->link('payment/wirecard', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL');
		$this->data['url_parcelamento_config'] = $this->url->link('payment/wirecard/getParcelamentoAvancado', 'token=' . $this->session->data['token'], 'SSL');
		$this->data['url_save'] = $this->url->link('payment/wirecard/save', 'token=' . $this->session->data['token'], 'SSL');
		$this->data['url_redirect_success'] = $this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL');
        $this->data['url_validate_credentials'] = $this->url->link('payment/wirecard/validateCredentials', 'token=' . $this->session->data['token'], 'SSL');
    if(isset($this->session->data['success'])){
      $this->data['success'] = $this->session->data['success'];
      unset($this->session->data['success']);
    }else{
      $this->data['success'] = false;
    }

    $this->document->setTitle($language['text_setting']);

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

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

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

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

    $config_data = array(
      'wirecard_status',
      'wirecard_token',
      'wirecard_key_access',
      'wirecard_key_public',
      'wirecard_ambiente',
      'wirecard_region',
      'wirecard_log_error',
      'wirecard_order',
      'wirecard_order_status_replicar',
      'wirecard_order_status_created',
      'wirecard_order_status_waiting',
      'wirecard_order_status_inanalysis',
      'wirecard_order_status_preauthorized',
      'wirecard_order_status_authorized',
      'wirecard_order_status_cancelled',
      'wirecard_order_status_refunded',
      'wirecard_order_status_reversed',
      'wirecard_order_status_settled',
      'wirecard_billet',
      'wirecard_credit_card',
      'wirecard_porcentagem_juros',
      'wirecard_parcela_minima',
      'wirecard_bank_transfer',
      'wirecard_discount',
      'wirecard_discount_order',
      'wirecard_cnpj',
      'wirecard_display',
      'wirecard_credit_card_title',
      'wirecard_bank_transfer_title',
      'wirecard_config_parcelamento',
      'wirecard_parcela_semjuros',
      'wirecard_parcela_comdesconto',
      'wirecard_parcela_desconto',
      'wirecard_parcela_qtdmax',
      'wirecard_parcelamento_configs'  ,
      'wirecard_parcela_juros'
    );

    foreach ($config_data as $conf) {
      if (isset($this->request->post[$conf])) {
        $this->data[$conf] = $this->request->post[$conf];
      } else {
        $this->data[$conf] = $this->config->get($conf);
      }
    }

    $logo_boleto = $this->dmodel_tool_image->resize('no_image.jpg', 80, 80);
    if (!empty($this->data['wirecard_billet'])) {
      array_walk($this->data['wirecard_billet'], function ($array) use ($logo_boleto) {
        if (isset($array['logo']) && (!empty($array['logo']))) {
            $logo_boleto = $this->dmodel_tool_image->resize(
                $array['logo'],
                Type_MiniatureMedium::Tp_width,
                Type_MiniatureMedium::Tp_height
            );
        }
      });
    }

    $logo = $this->config->get('config_logo');
    $logo_exists = file_exists(DIR_IMAGE . $logo) && is_file(DIR_IMAGE . $logo);
    $logo_preview = $logo && $logo_exists ? $logo : 'no_image.jpg';
    $this->data['logo'] = $this->dmodel_tool_image->resize(
        $logo_preview,
        Type_MiniatureMedium::Tp_width,
        Type_MiniatureMedium::Tp_height
    );

    $this->data['logo_boleto'] = $logo_boleto;
    $this->data['no_image'] = $this->dmodel_tool_image->resize('no_image.jpg', 100, 100);
    $this->data['typelogoboleto'] = Type_ImageUpload::Tp_WireCardLogoBoleto;

    $this->data['status_list'] = ftr_geral::getArrayTypes(Type_Status::getEnumList(), $this->data['wirecard_status'], Type_Status::Tp_Desabilitado);
    $this->data['environment_list'] = ftr_geral::getArrayTypes(Type_Environment::getEnumList(), $this->data['wirecard_ambiente'], Type_Environment::Tp_Production);
    $this->data['credit_cards'] = ftr_geral::getArrayTypes(Type_FormPgtoWirecardCartao::getEnumList(), null, null);
    $this->data['bank_transfers'] = ftr_geral::getArrayTypes(Type_FormPgtoWirecardTransferencia::getEnumList(), null, null);
    $this->data['billet'] = ftr_geral::getArrayTypes(Type_FormPgtoWirecardBoleto::getEnumList(), null, null);
    $this->data['status_list_error'] = ftr_geral::getArrayTypes(Type_Status::getEnumList(), $this->data['wirecard_log_error'], Type_Status::Tp_Desabilitado);
    $this->data['discount_type'] = ftr_geral::getArrayTypes(Type_MarketplaceAdjustmentPrice::getEnumList(), null, null);
    $this->data['discount_list'] = ftr_geral::getArrayTypes(Type_DsimDnao::getEnumList(), $this->data['wirecard_discount'], Type_DsimDnao::Tp_Nao);
    $this->data['display_module_options'] = ftr_geral::getArrayTypes(Type_DisplayModuleOption::getEnumList(), $this->data['wirecard_display'], Type_DisplayModuleOption::Tp_Todos);

    $this->load->model('localisation/geo_zone');
    $geo_zones = $this->model_localisation_geo_zone->getGeoZones();

    foreach ($geo_zones as $key => $value) {
      $this->data['geo_zones'][] = array(
        'id' => $value['geo_zone_id'],
        'name' => $value['name'],
        'status' => ftr_geral::isSelected($value['geo_zone_id'], $this->data['wirecard_region'])
      );
    }

    if ($this->config->get('processo_venda_status')) {
      $this->load->dmodel('proccess/order_to_situation');
      $this->data['order_statuses'] = $this->dmodel_proccess_order_to_situation->getProccessStatusAll();
    } else {
      $this->data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();
    }


    if($this->moip){
      $notifications = array();
      try {
        $result = $this->moip->notifications()->getList();

        foreach (get_object_vars($result->getNotifications()) as $notification) {
          $notifications[] = array(
            'id' => $notification->id,
            'url' => $notification->target
          );
        }
      } catch (Exception $e){
        $this->data['notifications'] = false;
        $this->error['error_warning'] = $e->getMessage();
      }

      $this->data['notifications'] = $notifications;
    }else{
      $this->data['notifications'] = false;
    }

    $config_error = array(
      'error_warning',
      'error_token',
      'error_key_access',
      'error_key_public',
      'error_total_parcela'
    );

    foreach ($config_error as $conf) {
      if (isset($this->error[$conf])) {
        $this->data[$conf] = $this->error[$conf];
      } else {
        $this->error[$conf] = '';
      }
    }

    $this->template = 'payment/wirecard.twig';

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

    $this->response->setOutput($this->render());

  }

	public function save(){
    $this->load->language('payment/wirecard');
		$response = array();
    if (!$this->user->hasPermission('modify', 'payment/wirecard')) {
      $this->error['error_warning'] = $this->language->get('error_permission');
    }

    $validate = $this->validate();
      if (count($validate) == 0) {
          $this->load->model('setting/setting');
            $this->removeMask(Type_CreditCardModule::getNickFromConstValue(Type_CreditCardModule::Wirecard));

            $credtcards = array();
            if ($this->request->post['wirecard_config_parcelamento']!=Type_ConfigParcelamento::PorBandeira and isset($this->request->post['wirecard_credit_card'])){
                foreach ($this->request->post['wirecard_credit_card'] as $key => $credtcard) {
                    $credtcards[$key]['valor_minimo'] = 0; /* O checkout padrão dos cartões possui valor minimo por bandeira, como módulo não tem essa config, ele é setado em 0 */
                    $credtcards[$key]['descricao'] = isset($credtcard['descricao']) ? $credtcard['descricao'] : '';
                }
                $this->request->post['wirecard_credit_card'] = $credtcards;
            }

      foreach ($this->request->post['wirecard_billet'] as $key => $values){
        if(!isset($values['status'])){
          $this->request->post['wirecard_billet'][$key]['status'] = 0;
        }
      }

      $arrayJson = array('wirecard_parcelamento_configs', 'wirecard_credit_card', 'wirecard_billet');
      $this->model_setting_setting->editSetting('wirecard', $this->request->post, 0, $arrayJson);

      $this->setPreferenceNotifications();
      
      $this->session->data['success'] = $this->language->get('text_success');
      $response['success'] = $this->language->get('text_success');
    } else {
      $response['errors'] = $validate;
    }
    
		$this->response->setOutputJson($response);
	}

	public function removeMask($module) {
        if(isset($this->request->post['wirecard_parcela_minima']) && $this->request->post['wirecard_parcela_minima']){
            $this->request->post['wirecard_parcela_minima'] = ftr_geral::removeMaskToDouble($this->request->post['wirecard_parcela_minima']);
        }

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

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

        if(isset($this->request->post['wirecard_billet']) and count($this->request->post['wirecard_billet'])){
            foreach ($this->request->post['wirecard_billet'] as $key => $value){
                $this->request->post['wirecard_billet'][$key]['valor_minimo'] = isset($value['valor_minimo'])? ftr_geral::removeMaskToDouble($value['valor_minimo']): 0;
            }
        }

        parent::removeMask($module);
	}

	public function getParcelamentoAvancado(){
		parent::getParcelamentoAvancado();
	}

  public function deleteNotification(){

    $json = array();

    if(isset($this->request->post['notification_id'])) {
      $notification_id = $this->request->post['notification_id'];
    }else {
      $json['warning'] = 'Id de notificação não encontrado';
    }

    $this->loadMoip();

    try{
      $this->moip->notifications()->delete($notification_id);
      $this->session->data['success'] = 'Preferência de notificação excluida com sucesso!';
      $json['success'] = true;
    }catch (Exception $e) {
      if($this->config->get('wirecard_log_error')){
          $this->log->write('Erro ao excluir preferência de notificação: '.$e->getMessage());
      }
      $json['warning'] = 'Erro ao excluir preferência de notificação!';
    }

    $this->response->setOutputJson($json);

  }

  protected function loadMoip($token = null, $key = null)
  {
    $token = $token ? $token : $this->config->get('wirecard_token');
    $key = $key ? $key : $this->config->get('wirecard_key_access');
    $url = ($this->config->get('wirecard_ambiente') == Type_Environment::Tp_Sandbox) ?  Moip::ENDPOINT_SANDBOX : Moip::ENDPOINT_PRODUCTION;

    if ($token && $key) {
      $this->moip = new Moip(new BasicAuth($token, $key), $url);
    }

  }

  protected function setPreferenceNotifications()
  {

    $this->loadMoip();

    if ($this->config->get('wirecard_status') && $this->moip ) {

      try {

        $notifications = $this->moip->notifications()->getList();

        foreach (get_object_vars($notifications->getNotifications()) as $notification) {
            $this->moip->notifications()->delete($notification->id);
        }

        $this->moip->notifications()->addEvent("PAYMENT.*")
            ->setTarget($this->urlloja->link('payment/wirecard/callback'))
            ->create();
      } catch (Exception $e){
        return false;
      }
    }

  }

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

    if (isset($this->request->post['wirecard_status']) && ($this->request->post['wirecard_status'] == Type_Status::Tp_Habilitado)) {

      if (empty($this->request->post['wirecard_token'])) {
        $this->error['wirecard_token'] = $this->language->get('error_wirecard_token');
      }

      if (empty($this->request->post['wirecard_key_access'])) {
        $this->error['wirecard_key_access'] = $this->language->get('error_wirecard_key_access');
      }

      if (empty($this->request->post['wirecard_key_public'])) {
        $this->error['wirecard_key_public'] = $this->language->get('error_wirecard_key_public');
      }

    }

    if ($this->request->post['wirecard_parcela_minima'] == ''){
      $this->request->post['wirecard_parcela_minima'] = 0;
    }

    if (empty($this->request->post['wirecard_parcela_qtdmax'])
        or $this->request->post['wirecard_parcela_qtdmax'] <= 0
        or $this->request->post['wirecard_parcela_qtdmax'] > Type_WirecardConfigs::Tp_MaximoParcela){
      $this->error['wirecard_parcela_qtdmax'] = $this->language->get('err_wirecard_parcela_qtdmax');
    }

    if ($this->request->post['wirecard_config_parcelamento'] == Type_ConfigParcelamento::Padrao){
        if ($this->request->post['wirecard_parcela_comdesconto'] > 0 && $this->request->post['wirecard_parcela_desconto']==0) {
            $this->error['wirecard_parcela_desconto'] = $this->language->get('err_wirecard_desconto');
        }else if($this->request->post['wirecard_parcela_comdesconto'] == 0 && $this->request->post['wirecard_parcela_desconto']>0) {
            $this->error['wirecard_parcela_comdesconto'] = $this->language->get('err_wirecard_desconto');
        }
    }

    if (  ($this->request->post['wirecard_config_parcelamento'] == Type_ConfigParcelamento::Padrao) && $this->request->post['wirecard_parcela_juros'] == 0 &&
    ($this->request->post['wirecard_parcela_qtdmax'] != (
        ($this->request->post['wirecard_parcela_semjuros'] ? $this->request->post['wirecard_parcela_semjuros'] : 0)
        +($this->request->post['wirecard_parcela_comdesconto'] ? $this->request->post['wirecard_parcela_comdesconto'] : 0)))
    ){
        $this->error['wirecard_parcela_qtdmax'] = $this->language->get('err_wirecard_parcela_maxima_total');
    }


    if(isset($this->request->post['wirecard_credit_card'])&& ($this->request->post['wirecard_config_parcelamento']==Type_ConfigParcelamento::PorBandeira)){
      $error_credit_cards = array();
      foreach($this->request->post['wirecard_credit_card'] as $key => $value){
        if(is_null(trim($value['total_parcela'])) || empty(trim($value['total_parcela']))){
          $error_credit_cards[$key]['total_parcela'] = $this->language->get('error_total_parcela');
        }
      }

      if($error_credit_cards){
        foreach ($error_credit_cards as $key => $error_credit_card){
          if(isset($error_credit_card['total_parcela'])){
            $this->error['wirecard_credit_card'][$key] = $error_credit_card;
          }
        }
        $this->error['error_warning'] = $this->language->get('error_warning_wirecard');
      }
    }

    if(count($this->error) > 0){
        $this->error['warning'] = $this->language->get('error_warning_wirecard');
    }

    $errorParcelamento = parent::parcelamentoValidate('wirecard');
    $this->error = array_merge($this->error,$errorParcelamento);
    return $this->error;
  }

  public function install()
  {
    $this->load->model('setting/extension');
    $this->load->model('setting/setting');

    $this->model_setting_extension->install('total', 'wirecard',Type_ExtensionSubType::Tp_TotalizadorAcrescimoDesconto);
    $this->model_setting_setting->insertSettingValue('wirecard', 'wirecard_cnpj', '08.718.431/0001-08');

  }

    public function uninstall()
    {
        $this->load->model('setting/extension');

        $this->model_setting_extension->uninstall('total', 'wirecard');

    }

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

        $token = $this->request->get['wirecard_token'];
        $key = $this->request->get['wirecard_key_access'];

        if (!$token || !$key) {
            $this->response->setOutputJson([
                'type' => 'error',
                'message' => $this->language->get('text_error_validate')
            ]);
        } else {
            $this->loadMoip($token, $key);

            try {
                $this->moip->notifications()->getList();

                $this->response->setOutputJson([
                    'type' => 'success',
                    'message' => $this->language->get('text_success_validate')
                ]);
            } catch (Exception $e) {
                $e->getMessage();

                $this->response->setOutputJson([
                    'type' => 'error',
                    'message' => $this->language->get('text_error_validate')
                ]);
            }
        }

    }


}