<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

$cep = preg_replace('/\D/', '', $_GET['cep'] ?? '');

if (strlen($cep) !== 8) {
    echo json_encode([
        'success' => false,
        'message' => 'CEP deve ter 8 dígitos'
    ]);
    exit;
}

// Buscar via ViaCEP
$url = "https://viacep.com.br/ws/{$cep}/json/";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode === 200 && $response) {
    $data = json_decode($response, true);

    if (isset($data['erro'])) {
        echo json_encode([
            'success' => false,
            'message' => 'CEP não encontrado'
        ]);
        exit;
    }

    echo json_encode([
        'success' => true,
        'data' => $data
    ]);
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Erro ao consultar CEP'
    ]);
}

