<?php

class ControllerTotalDescontoPrimeiraCompra extends Controller
{

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

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

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

        $this->data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();
        $this->data['Type_Status'] = Type_Status::getEnumList();
        $this->data['Type_DescontoPrimeiraCompra'] = Type_DescontoPrimeiraCompra::getEnumList();
        $this->data['Type_CadastroPessoa'] = Type_CadastroPessoa::getEnumList(true);

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

        $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/descontoprimeiracompra', 'token=' . $token . '&type=' . $this->request->get['type'], 'SSL'),
            ]
        ];

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

        if (!isset($configurations['descontoprimeiracompra_module'])) {
            $configurations['descontoprimeiracompra_module'] = [];
        }

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

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

        $this->removeMask();

        $response = [];

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

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

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

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

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

    private function removeMask()
    {
        if (!empty($this->request->post['descontoprimeiracompra_module'])) {
            $discounts = $this->request->post['descontoprimeiracompra_module'];

            foreach ($discounts as $discountKey => $discount) {
                $value_descont = ftr_geral::removeMaskToDouble($discount['value_descont']);
                $this->request->post['descontoprimeiracompra_module'][$discountKey]['value_descont'] = $value_descont;

                $value_minimo = ftr_geral::removeMaskToDouble($discount['value_minimo']);
                $this->request->post['descontoprimeiracompra_module'][$discountKey]['value_minimo'] = $value_minimo;
            }
        }
    }

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

        $errors = $this->validate->execute([
            'descontoprimeiracompra_status' => [
                'value' => $this->request->post['descontoprimeiracompra_status'],
                'validates' => ['isEmpty', 'isEnabledOrDisabled'],
            ],
            'descontoprimeiracompra_status_pedido' => [
                'value' => $this->request->post['descontoprimeiracompra_status_pedido'],
                'validates' => ['isEmpty', 'isOrderState'],
            ],
        ]);

        if (!empty($this->request->post['descontoprimeiracompra_module'])) {
            $discounts = $this->request->post['descontoprimeiracompra_module'];

            foreach ($discounts as $discountKey => $discount) {

                if(empty($this->request->post['descontoprimeiracompra_module'][$discountKey]['sort'])) {
                    $this->request->post['descontoprimeiracompra_module'][$discountKey]['sort'] = 0;
                }

                $discountErrors = $this->validate->execute([
                    'descontoprimeiracompra_module[' . $discountKey . '][title]' => [
                        'value' => $discount['title'],
                        'validates' => [
                            'isEmpty',
                            [
                                'method' => 'isMinMax',
                                'min' => 0,
                                'max' => 25
                            ]
                        ],
                    ],
                    'descontoprimeiracompra_module[' . $discountKey . '][type_descont]' => [
                        'value' => $discount['type_descont'],
                        'validates' => ['isEmpty'],
                    ],
                    'descontoprimeiracompra_module[' . $discountKey . '][value_descont]' => [
                        'value' => $discount['value_descont'],
                        'validates' => ['isEmpty'],
                    ],
                    'descontoprimeiracompra_module[' . $discountKey . '][type_person]' => [
                        'value' => $discount['type_person'],
                        'validates' => ['isEmpty'],
                    ],
                    'descontoprimeiracompra_module[' . $discountKey . '][sort]' => [
                        'value' => $discount['sort'],
                        'validates' => ['isIntegerNumber']
                    ],
                    'descontoprimeiracompra_module[' . $discountKey . '][status]' => [
                        'value' => $discount['status'],
                        'validates' => ['isEmpty', 'isEnabledOrDisabled']
                    ],
                ]);

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

        } else {
            $errors = $this->validate->execute([
                'descontoprimeiracompra_module' => [
                    'value' => '',
                    'validates' => ['errorModule']
                ]
            ]);
        }

        return $errors;
    }
}
