<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Cep extends CI_Controller{

    public function __construct() {
     parent::__construct();
    }
    
        public function recupera_cep() {
        
        $cep_request = $this->input->post('cep_code', TRUE);
        $cep_request = filter_var($cep_request, FILTER_SANITIZE_STRING);
        
        $credenciais = array(
            'token' => IMAZON_TOKEN,
            'chave' => IMAZON_CHAVE,
            'nome_instituicao' => IMAZON_INSTITUICAO,
        );
        
        $cep_response = $this->get_cep($credenciais, $cep_request);
        $response = json_decode($cep_response);
        
        if($response->status == '200'){
        //var_dump($response->response->nome_localidade);die;
            $cep = array(
            'logradouro'=>$response->response->endereco,
            'bairro'    =>$response->response->nome_bairro,
            'uf'        =>$response->response->sigla,
            'localidade'=>$response->response->nome_localidade,
            'numero'    =>''
            );
            
            //$response_entrega = $this->get_confirm_entrega($response->id_ent);
            
            echo json_encode($cep);
        }else{
            $cep = array(
            'logradouro'=>'',
            'bairro'    =>'',
            'uf'        =>'',
            'localidade'=>'',
            'numero'    =>''
            );
            
            echo json_encode($cep);
        }
       
    }
    
    private function get_cep($auth, $cep) {
        $auth['cep'] = $cep;
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, CEP_BUSCA_URL );
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $auth);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        
        $requisicao = curl_exec($ch);
        
        curl_close($ch);
        
        return $requisicao;
    }
    
    private function get_confirm_entrega($id_entrega) {
        
        $ch = curl_init();
        
        $post = array(
        'id_ent' => (String)$id_entrega,
        );
        //var_dump($post);die;
        curl_setopt($ch, CURLOPT_URL, CEP_ENTREGA_URL);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $entrega = curl_exec($ch);
        curl_close($ch);
        return $entrega;
    }
}