<?php
class ControllerShippingFree extends Controller {
    public function index() {
        $this->loadLanguage();

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

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

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

        $this->breadcrumbs();

        $this->data['Type_CadastroPessoa'] = Type_CadastroPessoa::getEnumList(true);
        $this->data['Type_Status'] = Type_Status::getEnumList();
        $this->data['geo_zones'] = $this->model_localisation_geo_zone->getGeoZones();

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

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

        $modules = $configurations['free_module'];
        foreach ($modules as $moduleKey => $module) {
            if (!isset($module['free_habilitar_pessoa_tipo'])) {
                $module['free_habilitar_pessoa_tipo'] = Type_CadastroPessoa::Tp_Ambos;
            }
        }

        $url_action = $this->url->link(
            'shipping/free/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' => $url_action,
            'back' => $url_back,
        ];

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

		$this->response->setOutput($this->render('shipping/free'));
    }

    public function save() {
        $this->loadLanguage();
        $this->removeMask();

        $response = [];

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

        $validate = $this->validate();
        if ($validate) {
            $response['errors'] = $validate;
            return $this->response->setOutputJson($response);
        }

        $this->load->model('setting/setting');
        $this->model_setting_setting->editSetting('free', $this->request->post);
        $this->session->data['success'] = $this->language->get('text_success');
        $response['success'] = $this->language->get('text_success');

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

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

            foreach ($modules as $moduleKey => $module) {
                $valueTotal = ftr_geral::removeMaskToDouble($module['free_total']);
                $this->request->post['free_module'][$moduleKey]['free_total'] = $valueTotal;

                $valueTypePerson = $module['free_habilitar_pessoa_tipo'];
                $this->request->post['free_module'][$moduleKey]['free_habilitar_pessoa_tipo'] =
                    !isset($valueTypePerson)
                    ? Type_CadastroPessoa::Tp_Ambos
                    : $valueTypePerson;
            }
        }
    }

	public function install() {
        $this->load->model('setting/setting');
        $this->model_setting_setting->editSetting('free', array('free_habilitar_pessoa_tipo' => '2'));
    }

    private function breadcrumbs() {
        $token = $this->session->data['token'];
        $type = $this->request->get['type'];

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

    private function loadLanguage() {
        $language = $this->language->load('shipping/free');
        $this->data = array_merge($this->data, $language);
    }

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

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

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

            foreach ($modules as $moduleKey => $module) {
                $moduleErrors = $this->validate->execute([
                    'free_module[' .  $moduleKey . '][free_titlefutura]' => [
                        'value' => $module['free_titlefutura'],
                        'validates' => ['isEmpty', 'isWithoutDot'],
                    ],
                    'free_module[' .  $moduleKey . '][free_habilitar_pessoa_tipo]' => [
                        'value' => $module['free_habilitar_pessoa_tipo'],
                        'validates' => ['isEmpty'],
                    ],
                    'free_module[' .  $moduleKey . '][free_total]' => [
                        'value' => $module['free_total'],
                        'validates' => ['isEmpty'],
                    ],
                    'free_module[' .  $moduleKey . '][free_geo_zone_id]' => [
                        'value' => $module['free_geo_zone_id'],
                        'validates' => ['isEmpty'],
                    ],
                    'free_module[' .  $moduleKey . '][free_status]' => [
                        'value' => $module['free_status'],
                        'validates' => ['isEmpty', 'isEnabledOrDisabled']
                    ],
                ]);

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

        return $errors;
	}
}
