<?php
class ControllerTotaldescontoporpagamento extends Controller {
	public function index() {
		$language = $this->load->language('total/descontoporpagamento');
		$this->data = array_merge($this->data, $language);

    $this->document->setTitle($this->language->get('heading_title'));
    $this->document->addScript('admin/public/js/total/descontoporpagamento.js');

    $this->load->model('setting/setting');
    $this->load->dmodel('sale/customer_group');
		$this->load->model('setting/extension');

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

    $this->data['Type_Status'] = Type_Status::getEnumList();

    $this->data['breadcrumbs'] = [
      [
        'text' => $this->language->get('text_home'),
        'href' => $this->url->link('common/home', 'token=' . $token, 'SSL'),
      ],
      [
        'text' => $this->language->get('text_total'),
        'href' => $this->url->linkAnchor('extension/module', 'token=' . $token, 'tab-info=' . $this->request->get['type'], 'SSL'),
      ],
      [
        'text' => $this->language->get('heading_title'),
        'href' => $this->url->link('total/descontoporpagamento', 'token=' . $token . '&type=' . $this->request->get['type'], 'SSL'),
      ]
    ];


		$this->data['tipos_pagamento'] = [];

		$payments = $this->model_setting_extension->getInstalled('payment', Type_ExtensionSubType::Tp_Payment);
		foreach ($payments as $payment) {
      $this->language->load('payment/' . $payment);
      $this->data['tipos_pagamento'][] = [
        'arquivo' => $payment,
        'title' => $this->language->get('heading_title')
      ];
    }

    $configurations = $this->model_setting_setting->getSetting('descontoporpagamento');

    if (isset($configurations['desconto_tipo_pagamento'])) {
      /* Retrocompatibilidade: Ajusta o retorno da tabela_preco
      ** Antes: tabela_preco => [tabelapreco1 => '1', tabelapreco2 => '2'];
      ** Depois: tabela_preco => ['1', '2'];
      */
      $discounts = $configurations['desconto_tipo_pagamento'];
      $newDiscounts = [];
      foreach ($discounts as $discountKey => $discount) {
        $fixTablePrice = [];

        if (!empty($discount['tabela_preco'])) {
          foreach ($discount['tabela_preco'] as $tablePriceKey => $tablePrice) {
            $fixTablePrice[] = $tablePrice;
          }
        }

        $configurations['desconto_tipo_pagamento'][$discountKey]['tabela_preco'] = $fixTablePrice;

        /* Retrocompatibilidade
        ** Antes: desconto_tipo_pagamento => ['0' => objeto] (Objeto)
        ** Depois: desconto_tipo_pagamento => [0 => objeto] (Array)
        */
        $newDiscounts[] = $configurations['desconto_tipo_pagamento'][$discountKey];
      }
      $configurations['desconto_tipo_pagamento'] = $newDiscounts;
    } else {
      $configurations['desconto_tipo_pagamento'] = [];
    }

    $customerGroups = $this->dmodel_sale_customer_group->getCustomerGroups();

    $url_action = $this->url->link(
      'total/descontoporpagamento/save',
      'token=' . $token . '&type=' . $this->request->get['type'],
      'SSL'
    );

		$url_back = $this->url->linkAnchor(
      'extension/module',
      'token=' . $token,
      'tab-info=' . $this->request->get['type'],
      'SSL'
    );

    $this->data['data'] = [
      'configurations' => $configurations,
      'customerGroups' => $customerGroups,
      'action' => str_replace('&amp;', '&', $url_action),
      'back' => str_replace('&amp;', '&', $url_back),
    ];

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


		$this->response->setOutput($this->render('total/descontoporpagamento'));
  }

  public function save() {
    $language = $this->load->language('total/descontoporpagamento');
    $this->data = array_merge($this->data, $language);

    $response = [];

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

    $this->removeMask();

    if (!$this->validate()) {
      $this->load->model('setting/setting');

			$this->model_setting_setting->editSetting('descontoporpagamento', $this->request->post);

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

    return $this->response->setOutputJson($response);
  }

  private function removeMask() {
    $discounts = $this->request->post['desconto_tipo_pagamento'];

    foreach ($discounts as $discountsKey => $discount) {
      $val_desconto = ftr_geral::removeMaskToDouble($discount['val_desconto']);
      $this->request->post['desconto_tipo_pagamento'][$discountsKey]['val_desconto'] = $val_desconto;

      $valor_minimo = ftr_geral::removeMaskToDouble($discount['valor_minimo']);
      $this->request->post['desconto_tipo_pagamento'][$discountsKey]['valor_minimo'] = $valor_minimo;
    }
  }

	private function validate() {

    $errors = [];
    $targetIsDuplicatedObject = '';
    $desconto_tipo_pagamento_Habilitado = [] ;

    $errors = $this->validate->execute([
      'descontoporpagamento_status' => [
        'value' => $this->request->post['descontoporpagamento_status'],
        'validates' => ['isEmpty', 'isEnabledOrDisabled'],
      ],
      'descontoporpagamento_sort_order' => [
        'value' => $this->request->post['descontoporpagamento_sort_order'],
        'validates' => ['isIntegerNumber'],
      ],
    ]);

    $discounts = $this->request->post['desconto_tipo_pagamento'];
    foreach ($discounts as $discountsKey => $discount) {

        if($discount['status_desconto'] == Type_Status::Tp_Habilitado){
            array_push($desconto_tipo_pagamento_Habilitado , $discount);
        }

      $discountErrors = $this->validate->execute([
        'desconto_tipo_pagamento[' .  $discountsKey . '][pagamento_desconto]' => [
          'value' => $discount['pagamento_desconto'],
          'validates' => ['isEmpty'],
        ],
        'desconto_tipo_pagamento[' .  $discountsKey . '][val_desconto]' => [
          'value' => $discount['val_desconto'],
          'validates' => [
            'isEmpty',
            [
              'method' => 'isMinMaxNumber',
              'min' => 0,
              'max' => 100
            ]
          ],
        ],
        'desconto_tipo_pagamento[' .  $discountsKey . '][status_desconto]' => [
          'value' => $discount['status_desconto'],
          'validates' => ['isEmpty', 'isEnabledOrDisabled'],
        ],
        'desconto_tipo_pagamento[' .  $discountsKey . '][valor_minimo]' => [
          'value' => $discount['valor_minimo'],
          'validates' => ['isEmpty', 'isIntegerNumber'],
        ],
        'desconto_tipo_pagamento[' .  $discountsKey . '][prioridade_desconto]' => [
          'value' => $discount['prioridade_desconto'],
          'validates' => ['isEmpty', 'isIntegerNumber'],
        ],
      ]);

      if ($discountErrors) {
        $errors = array_merge($errors, $discountErrors);
      }

    }

    $targetIsDuplicatedObject = $this->validate->targetIsDuplicatedObject(
        $desconto_tipo_pagamento_Habilitado,
        $this->language->get('error_duplicate'),
        ["prioridade_desconto"]
    );

    if($targetIsDuplicatedObject){
        $errors['message'] = $targetIsDuplicatedObject;


    } else if($errors){
        $errors['message'] = $this->language->get('error_message');
    }

    return $errors;
	}
}
