<?php

class ControllerModuleSkyhubAccount extends Controller
{

    public function apply()
    {

        $this->load->language('module/skyhub/account');

        $json['error'] = $this->validate();

        if (!$json['error']) {

            $skyhub = new SkyHub($this->registry);

            $dataAccount = array(
                'sellerId' => preg_replace('/([^0-9])/i', '', $this->request->post['config_cnpj']),
                'platform' => 'Opencart',
                'state_register' => preg_replace('/([^0-9])/i', '', $this->request->post['config_ie']),
                'contact' => array(
                    'type' => 'PRINCIPAL',
                    'phone' => preg_replace('/([^0-9])/i', '', (isset($this->request->post['telephone'])) ? $this->request->post['telephone'] : ''),
                    'name' => $this->request->post['name'],
                    'email' => $this->request->post['email'],
                    'document' => $this->request->post['document'],
                    'cellphone' => preg_replace('/([^0-9])/i', '', (isset($this->request->post['cellphone'])) ? $this->request->post['cellphone'] : '')
                )
            );

            $result = $skyhub->createAccountB2w($dataAccount);

            if ($result) {
                $json['success'] = $this->language->get('text_success');
            } else {
                if ($skyhub->httpcode == TypeSkyHubHttpCode::Tp_ErroSemantico) {
                    $json['warning'] = 'O ' . $this->request->post['config_cnpj'] . ' já possui uma conta.';
                } else {
                    $json['warning'] = $this->language->get('text_warning');
                }
            }

        }

        $this->response->setOutputJson($json);

    }

    public function validate()
    {

        $this->load->helper('ftr_validacao');

        $error = array();

        $cnpj = preg_replace('/([^0-9])/i', '', $this->request->post['config_cnpj']);
        if ((strlen(utf8_decode($cnpj)) < 1) || (strlen(utf8_decode($cnpj)) > 18)) {
            $error['config_cnpj'] = "O CNPJ não deve passar de 18 caracteres";
        } else if (!ftr_validacao::isCnpj($cnpj)) {
            $error['config_cnpj'] = "O CNPJ informado é inválido";
        }

        if (isset($this->request->post['config_ie']) && ($this->request->post['config_ie'] == '') || ((strlen($this->request->post['config_ie']) < 1))) {
            $error['config_ie'] = "Informe a Inscrição Estadual";
        }

        if ((utf8_strlen($this->request->post['email']) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $this->request->post['email']) || !filter_var($this->request->post['email'], FILTER_VALIDATE_EMAIL) || !preg_match('/^[a-zA-Z0-9\._-]+@/', $this->request->post['email'])) {
            $error['email'] = $this->language->get('error_email');
        }

        return $error;

    }


}