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

        $this->document->setTitle("Transportadora Jamef");
        $this->document->addScript('admin/public/js/shipping/jamef.js');

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

        $token = $this->session->data['token'];
        $country_id = Type_PaisId::Tp_Brasil;

        $this->load->type('tipocomum');
        $this->data['Type_CodFilialJamef'] = Type_CodFilialJamef::getEnumList();
        $this->data['Type_ProdutoJameF'] = Type_ProdutoJameF::getEnumList();

        $this->data['geo_zones'] = $this->model_localisation_geo_zone->getGeoZones();
        $this->data['zones'] = $this->model_localisation_zone->getZonesByCountryId($country_id);

        $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=' . $this->request->get['type'], 'SSL'),
            ],
            [
                'text' => $this->language->get('heading_title'),
                'href' => $this->url->link('shipping/jamef', 'token=' . $token . '&type=' . $this->request->get['type'], 'SSL'),
            ]
        ];

        $url_action = $this->url->link(
            'shipping/jamef/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'
        );

        $url_cities = $this->urlloja->link(
            'postcode/postcode/listCities',
            'token=' . $token,
            'SSL'
        );

        $configurations = $this->model_setting_setting->getSetting('jamef');
        $uf = isset($configurations['jamef_ufOrigem']) ? $configurations['jamef_ufOrigem'] : 'SP';

        $zoneIndex = array_search($uf, array_column($this->data['zones'], 'code'));
        $param['zone_id'] = $this->data['zones'][$zoneIndex]['zone_id'];

        // Falei com o matheus, pra retirar a verificação de SSL dessa chamada
        $requestApi = new RestApi;
        $requestApi->setcurlOpts([CURLOPT_RETURNTRANSFER => 1, CURLOPT_SSL_VERIFYPEER => 0, CURLOPT_SSL_VERIFYHOST => 0]);
        $responseCities = $requestApi->callAPI(
            $url_cities,
            'POST',
            $param,
            array(),
            false,
            $retorno,
            Type_DadosSend::TpDados_Identificar
        );
        
        if (isset($responseCities)) {
          $cities = $responseCities->cities;
          $cities = array_map(function ($city) {
            return [
              'municipio' => $city->municipio
            ];
          }, $cities);
        }

        $this->data['data'] = [
            'configurations' => $configurations,
            'action' => $url_action,
            'back' => $url_back,
            'zones' => $this->data['zones'],
            'urlCities' => $url_cities,
            'cities' => $cities,
        ];

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

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

    public function save() {
        $response = array();

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

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

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

            $this->session->data['success'] = "Dados salvos com sucesso!";
            $response['success'] = "Dados salvos com sucesso!";
        } else {
            $response['errors'] = $this->validate();
        }

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

    private function removeMask() {
        $this->request->post['jamef_cnpj'] = ftr_geral::removeMaskToInt($this->request->post['jamef_cnpj']);
    }

    private function validate() {
        extract($this->request->post);

        return $this->validate->execute([
            'jamef_nome' => [
                'value' => $jamef_nome,
                'validates' => [
                    'isEmpty',
                    [
                        'method' => 'isMinMax',
                        'min' => 1,
                        'max' => 32
                    ]
                ],
            ],
            'jamef_cnpj' => [
                'value' => $jamef_cnpj,
                'validates' => ['isEmpty', 'isCnpj'],
            ],
            'jamef_municipioOrigem' => [
                'value' => $jamef_municipioOrigem,
                'validates' => [
                    'isEmpty',
                    [
                        'method' => 'isMinMax',
                        'min' => 1,
                        'max' => 32
                    ]
                ],
            ],
            'jamef_ufOrigem' => [
                'value' => $jamef_ufOrigem,
                'validates' => ['isEmpty','isUf'],
            ],
        ]);
	}
}
