<?php
require __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . DS . 'simple_html_dom.php';
use GuzzleHttp\Client;

class ConsultaSimplesNacional {

    private static function getUserAgent() {
        $agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36';
        return isset($_SERVER['USER_AGENT']) && !empty($_SERVER['USER_AGENT']) ? $_SERVER['USER_AGENT'] : $agent;
    }
    /**
     * Devolve um array de parâmetros para consulta de CNPJ Simples Nacional
     * @return array
     */
    public static function getParams() {
        $client = new Client(['verify' => false,'timeout' => 1]);
        $param = [
            'headers' => [
                'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'Accept-Encoding' => 'gzip, deflate, sdch',
                'Accept-Language' => 'pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4',
                'Connection' => 'keep-alive',
                'Content-type' => 'application/x-www-form-urlencoded',
                'Host' => 'www8.receita.fazenda.gov.br',
                'Origin' => 'http://www8.receita.fazenda.gov.br',
                'Referer' => 'http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/ConsultarOpcao.aspx',
                'Cache-Control'=>'max-age=0',
                'Connection'=>'keep-alive',
                'Content-type'=>'application/x-www-form-urlencoded',
                'Host'=>'www8.receita.fazenda.gov.br',
                'Referer'=>'http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/ConsultarOpcao.aspx',
                'User-Agent' => self::getUserAgent()
            ],
            'timeout' => 20, // Response timeout
            'connect_timeout' => 20, // Connection timeout
        ];

        $response = $client->request('GET', 'http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/ConsultarOpcao.aspx', $param);

        $html = str_get_html($response->getBody());
        $inputViewStateValue = $html->getElementById('__VIEWSTATE')->value;
        //$inputEventValidationValue = $html->getElementById('__EVENTVALIDATION')->value;
        $viewStateGeneratorValue = $html->getElementById('__VIEWSTATEGENERATOR')->value;
        $inputHiddenField1Value = $html->getElementById('ctl00_ContentPlaceHolderConteudo_HiddenField1')->value;
        $inputHddServidorCaptchaValue = $html->getElementById('hddServidorCaptcha')->value;
        $urlCaptchaContainer = $html->getElementById('captcha-container')->{'data-url'};
        $html->clear();

        $response = $client->request('GET', 'http://www8.receita.fazenda.gov.br/'.$urlCaptchaContainer . '/Captcha/Inicializa.ashx', $param);
        $cookies = $response->getHeader('Set-Cookie');
        $cookies = explode(';', $cookies[0]);
        $cookie = $cookies[0];

        $jsonResponse = json_decode($response->getBody());
        $imgReturn = 'data:image/png;base64,' . $jsonResponse->Dados;
        return [
            'cookie' => 'captcha_token=' . $jsonResponse->Token . '; '.$cookie,
            'viewState' => $inputViewStateValue,
            'hiddenField1' => $inputHiddenField1Value,
            'hddServidorCaptcha' => $inputHddServidorCaptchaValue,
            'captchaBase64' => $imgReturn
        ];
    }

    public static function consulta($cnpj, $captcha, $stringCookie, $viewState, $hiddenField, $servidorCaptcha) {
        $client = new Client(['verify' => false,'timeout' => 1]);
        $param = [
            'form_params' => [
                '__EVENTTARGET' => null,
                '__EVENTARGUMENT' => null,
                '__VIEWSTATE' => $viewState,
                "ctl00\$ContentPlaceHolderConteudo\$$hiddenField" => $cnpj,
                'ctl00$ContentPlaceHolderConteudo$HiddenField1' => $hiddenField,
                'ctl00$ContentPlaceHolderConteudo$hddServidorCaptcha' => $servidorCaptcha,
                'ctl00$ContentPlaceHolderConteudo$txtTexto_captcha_serpro_gov_br' => $captcha,
                'ctl00$ContentPlaceHolderConteudo$btnConfirmar' => 'Consultar'
            ],
            'headers' => [
                'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'Accept-Encoding' => 'gzip, deflate, sdch',
                'Accept-Language' => 'pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4',
                'Connection' => 'keep-alive',
                'Content-type' => 'application/x-www-form-urlencoded',
                'Cookie' => $stringCookie,
                'Host' => 'www8.receita.fazenda.gov.br',
                'Origin' => 'http://www8.receita.fazenda.gov.br',
                'Referer' => 'http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/ConsultarOpcao.aspx',
                'User-Agent' => self::getUserAgent()
            ],
            'timeout' => 20, // Response timeout
            'connect_timeout' => 20, // Connection timeout
        ];
        $response = $client->request('POST', 'http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/ConsultarOpcao.aspx', $param);

        $html = str_get_html($response->getBody());
        if(!is_object($html)) {
            throw new \Exception('Não foi possível buscar os dados do simples nacional, por favor, tente novamente!', 99);
        }
        $erros = $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblErroCaptcha');
        if (is_object($erros)) {
            throw new \Exception(utf8_decode($erros->plaintext), 99);
        }
        $situacao = $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblSituacaoSimples');
        if(!is_object($situacao)) {
            throw new \Exception('Erro ao buscar dados no site do simples nacional, por favor, tente novamente!', 99);
        }
        return [
            'situacao_simples_nacional' => trim(utf8_decode($situacao->plaintext)),
            'code' => 0
        ];
    }
}