<?php


class ControllerTotalacrescimoporpagamento extends Controller
{
    public function index()
    {
        $language = $this->load->language('total/acrescimoporpagamento');
        $this->data = array_merge($this->data, $language);

        $this->document->setTitle($this->language->get('heading_title'));
        $this->document->addScript('admin/public/js/total/acrescimoporpagamento.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/acrescimoporpagamento', '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('acrescimoporpagamento');

        if (isset($configurations['acrescimo_tipo_pagamento'])) {
            /* Retrocompatibilidade: Ajusta o retorno da tabela_preco
            ** Antes: tabela_preco => [tabelapreco1 => '1', tabelapreco2 => '2'];
            ** Depois: tabela_preco => ['1', '2'];
            */
            $increases = $configurations['acrescimo_tipo_pagamento'];
            $newIncreases = [];
            foreach ($increases as $increaseKey => $increase) {
                $fixTablePrice = [];

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

                $configurations['acrescimo_tipo_pagamento'][$increaseKey]['tabela_preco'] = $fixTablePrice;

                /* Retrocompatibilidade
                ** Antes: acrescimo_tipo_pagamento => ['0' => objeto] (Objeto)
                ** Depois: acrescimo_tipo_pagamento => [0 => objeto] (Array)
                */
                $newIncreases[] = $configurations['acrescimo_tipo_pagamento'][$increaseKey];
            }
            $configurations['acrescimo_tipo_pagamento'] = $newIncreases;
        } else {
            $configurations['acrescimo_tipo_pagamento'] = [];
        }

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

        $url_action = $this->url->link(
            'total/acrescimoporpagamento/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/acrescimoporpagamento'));
    }

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

        $response = [];

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

        $this->removeMask();

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

            $this->model_setting_setting->editSetting('acrescimoporpagamento', $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()
    {
        $increases = $this->request->post['acrescimo_tipo_pagamento'];

        foreach ($increases as $increasesKey => $increase) {
            $val_acrescimo = ftr_geral::removeMaskToDouble($increase['val_acrescimo']);
            $this->request->post['acrescimo_tipo_pagamento'][$increasesKey]['val_acrescimo'] = $val_acrescimo;

            $valor_minimo = ftr_geral::removeMaskToDouble($increase['valor_minimo']);
            $this->request->post['acrescimo_tipo_pagamento'][$increasesKey]['valor_minimo'] = $valor_minimo;
        }
    }

    private function validate(){
        $targetIsDuplicatedObject = '';
        $errors = [];
        $acrescimo_tipo_pagamento_Habilitado = [] ;

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

        $increases = $this->request->post['acrescimo_tipo_pagamento'];
        foreach ($increases as $increasesKey => $increase) {

            if($increase['status_acrescimo'] == Type_Status::Tp_Habilitado){
                array_push($acrescimo_tipo_pagamento_Habilitado , $increase);
            }

            $increaseErrors = $this->validate->execute([
                'acrescimo_tipo_pagamento[' . $increasesKey . '][pagamento_acrescimo]' => [
                    'value' => $increase['pagamento_acrescimo'],
                    'validates' => ['isEmpty'],
                ],
                'acrescimo_tipo_pagamento[' . $increasesKey . '][val_acrescimo]' => [
                    'value' => $increase['val_acrescimo'],
                    'validates' => [
                        'isEmpty',
                        [
                            'method' => 'isMinMaxNumber',
                            'min' => 0,
                            'max' => 100
                        ]
                    ],
                ],
                'acrescimo_tipo_pagamento[' . $increasesKey . '][status_acrescimo]' => [
                    'value' => $increase['status_acrescimo'],
                    'validates' => ['isEmpty', 'isEnabledOrDisabled'],
                ],
                'acrescimo_tipo_pagamento[' . $increasesKey . '][valor_minimo]' => [
                    'value' => $increase['valor_minimo'],
                    'validates' => ['isEmpty', 'isIntegerNumber'],
                ],
                'acrescimo_tipo_pagamento[' . $increasesKey . '][prioridade_acrescimo]' => [
                    'value' => $increase['prioridade_acrescimo'],
                    'validates' => ['isEmpty', 'isIntegerNumber'],
                ],
            ]);

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

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


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


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




        return $errors;
    }
}
