<?php
/**
 * Meus Endereços - MontaLoja
 * Gerenciamento de endereços do cliente
 */

require_once __DIR__ . '/includes/store-config.php';

// Verificar se está logado
if (!isCustomerLoggedIn()) {
    $_SESSION['redirect_after_login'] = storeUrl('meus-enderecos');
    header("Location: " . storeUrl('entrar'));
    exit;
}

$customer = getLoggedCustomer();
$customerId = $customer['id'];

// Processar ações
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'save') {
        $addressId = $_POST['address_id'] ?? null;
        $label = trim($_POST['label'] ?? '');
        $cep = preg_replace('/[^0-9]/', '', $_POST['cep'] ?? '');
        $street = trim($_POST['street'] ?? '');
        $number = trim($_POST['number'] ?? '');
        $complement = trim($_POST['complement'] ?? '');
        $neighborhood = trim($_POST['neighborhood'] ?? '');
        $city = trim($_POST['city'] ?? '');
        $state = trim($_POST['state'] ?? '');
        $isDefault = isset($_POST['is_default']) ? 1 : 0;
        
        if (empty($cep) || empty($street) || empty($number) || empty($neighborhood) || empty($city) || empty($state)) {
            $message = 'Por favor, preencha todos os campos obrigatórios.';
            $messageType = 'error';
        } else {
            try {
                // Se marcar como padrão, desmarcar os outros
                if ($isDefault) {
                    $pdo->prepare("UPDATE customer_addresses SET is_default = 0 WHERE customer_id = ?")->execute([$customerId]);
                }
                
                if ($addressId) {
                    // Atualizar endereço existente
                    $stmt = $pdo->prepare("UPDATE customer_addresses SET label = ?, cep = ?, street = ?, number = ?, complement = ?, neighborhood = ?, city = ?, state = ?, is_default = ? WHERE id = ? AND customer_id = ?");
                    $stmt->execute([$label, $cep, $street, $number, $complement, $neighborhood, $city, $state, $isDefault, $addressId, $customerId]);
                    $_SESSION['flash_message'] = 'Endereço atualizado com sucesso!';
                } else {
                    // Criar novo endereço
                    $stmt = $pdo->prepare("INSERT INTO customer_addresses (customer_id, store_id, label, cep, street, number, complement, neighborhood, city, state, is_default) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$customerId, $currentStoreId, $label, $cep, $street, $number, $complement, $neighborhood, $city, $state, $isDefault]);
                    $_SESSION['flash_message'] = 'Endereço cadastrado com sucesso!';
                }
                $_SESSION['flash_type'] = 'success';
                header("Location: " . storeUrl('meus-enderecos'));
                exit;
            } catch (Exception $e) {
                $message = 'Erro ao salvar endereço. Tente novamente.';
                $messageType = 'error';
            }
        }
    }
    
    if ($action === 'delete') {
        $addressId = $_POST['address_id'] ?? null;
        if ($addressId) {
            $stmt = $pdo->prepare("DELETE FROM customer_addresses WHERE id = ? AND customer_id = ?");
            $stmt->execute([$addressId, $customerId]);
            $_SESSION['flash_message'] = 'Endereço removido com sucesso!';
            $_SESSION['flash_type'] = 'success';
            header("Location: " . storeUrl('meus-enderecos'));
            exit;
        }
    }
    
    if ($action === 'set_default') {
        $addressId = $_POST['address_id'] ?? null;
        if ($addressId) {
            $pdo->prepare("UPDATE customer_addresses SET is_default = 0 WHERE customer_id = ?")->execute([$customerId]);
            $pdo->prepare("UPDATE customer_addresses SET is_default = 1 WHERE id = ? AND customer_id = ?")->execute([$addressId, $customerId]);
            $_SESSION['flash_message'] = 'Endereço padrão alterado!';
            $_SESSION['flash_type'] = 'success';
            header("Location: " . storeUrl('meus-enderecos'));
            exit;
        }
    }
}

// Verificar mensagens flash da sessão
if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    $messageType = $_SESSION['flash_type'] ?? 'success';
    unset($_SESSION['flash_message'], $_SESSION['flash_type']);
}

// Buscar endereços do cliente
$stmt = $pdo->prepare("SELECT * FROM customer_addresses WHERE customer_id = ? ORDER BY is_default DESC, created_at DESC");
$stmt->execute([$customerId]);
$addresses = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Estados brasileiros
$states = ['AC', 'AL', 'AP', 'AM', 'BA', 'CE', 'DF', 'ES', 'GO', 'MA', 'MT', 'MS', 'MG', 'PA', 'PB', 'PR', 'PE', 'PI', 'RJ', 'RN', 'RS', 'RO', 'RR', 'SC', 'SP', 'SE', 'TO'];
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Meus Endereços - <?php echo htmlspecialchars($storeName); ?></title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/iconify-icon@1.0.7/dist/iconify-icon.min.js"></script>
<link rel="stylesheet" href="/pages/storefront/templates/retail/modern/includes/styles.css?v=1.0.4">
<?php include __DIR__ . "/includes/dynamic-styles.php"; ?>
<style>
/* Dynamic Color Variables from Store Settings */
:root {
    --primary: <?php echo htmlspecialchars($primaryColor ?? '#2563EB'); ?>;
    --primary-soft: <?php echo htmlspecialchars($primaryColor ?? '#2563EB'); ?>14;
    --primary-hover: <?php echo htmlspecialchars($customSettings['colors']['secondary'] ?? $primaryColor ?? '#1D4ED8'); ?>;
    --accent: <?php echo htmlspecialchars($accentColor ?? '#10B981'); ?>;
    --accent-soft: <?php echo htmlspecialchars($accentColor ?? '#10B981'); ?>1A;
    --bg: <?php echo htmlspecialchars($bgColor ?? '#FAFBFC'); ?>;
    --bg-white: <?php echo htmlspecialchars($cardColor ?? '#FFFFFF'); ?>;
    --surface: <?php echo htmlspecialchars($cardColor ?? '#FFFFFF'); ?>;
    --text: <?php echo htmlspecialchars($textColor ?? '#111827'); ?>;
    --text-secondary: <?php echo htmlspecialchars($textSecondary ?? '#6B7280'); ?>;
}

.page-container {
    max-width: 900px;
    margin: 0 auto;
    padding: 24px;
}

.page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24px;
    flex-wrap: wrap;
    gap: 16px;
}

.page-title {
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 1.75rem;
    font-weight: 800;
    color: var(--text);
}

.page-title iconify-icon {
    color: var(--primary);
}

.back-link {
    display: flex;
    align-items: center;
    gap: 8px;
    color: var(--text-secondary);
    text-decoration: none;
    font-weight: 500;
    transition: color 0.2s;
}

.back-link:hover {
    color: var(--primary);
}

/* Alert Messages */
.alert {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 16px;
    border-radius: var(--radius);
    margin-bottom: 24px;
    font-weight: 500;
}

.alert.success {
    background: rgba(16, 185, 129, 0.1);
    color: #10B981;
    border: 1px solid rgba(16, 185, 129, 0.2);
}

.alert.error {
    background: rgba(239, 68, 68, 0.1);
    color: #EF4444;
    border: 1px solid rgba(239, 68, 68, 0.2);
}

/* Add Address Button */
.btn-add-address {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 14px 24px;
    background: var(--primary);
    color: white;
    border: none;
    border-radius: 50px;
    font-weight: 600;
    font-size: 0.95rem;
    cursor: pointer;
    transition: all 0.2s;
}

.btn-add-address:hover {
    background: var(--primary-hover);
    transform: translateY(-2px);
}

/* Addresses Grid */
.addresses-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 20px;
}

.address-card {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: var(--radius-lg);
    padding: 20px;
    position: relative;
    transition: all 0.2s;
}

.address-card:hover {
    border-color: var(--primary);
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}

.address-card.default {
    border-color: var(--primary);
    background: linear-gradient(135deg, rgba(var(--primary-rgb), 0.05), transparent);
}

.address-label {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;
}

.address-label h3 {
    font-size: 1.1rem;
    font-weight: 700;
    color: var(--text);
}

.badge-default {
    padding: 4px 10px;
    background: var(--primary);
    color: white;
    border-radius: 50px;
    font-size: 0.75rem;
    font-weight: 600;
}

.address-content {
    color: var(--text-secondary);
    font-size: 0.95rem;
    line-height: 1.6;
    margin-bottom: 16px;
}

.address-content strong {
    color: var(--text);
}

.address-actions {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.btn-action {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 8px 14px;
    border-radius: var(--radius);
    font-weight: 500;
    font-size: 0.85rem;
    cursor: pointer;
    transition: all 0.2s;
    border: none;
    text-decoration: none;
}

.btn-action.edit {
    background: var(--surface-hover);
    color: var(--text);
}

.btn-action.edit:hover {
    background: var(--primary);
    color: white;
}

.btn-action.delete {
    background: rgba(239, 68, 68, 0.1);
    color: #EF4444;
}

.btn-action.delete:hover {
    background: #EF4444;
    color: white;
}

.btn-action.default {
    background: var(--surface-hover);
    color: var(--text-secondary);
}

.btn-action.default:hover {
    background: var(--primary);
    color: white;
}

/* Empty State */
.empty-state {
    text-align: center;
    padding: 64px 24px;
    background: var(--surface);
    border-radius: var(--radius-lg);
    border: 1px solid var(--border);
}

.empty-icon {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background: var(--surface-hover);
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 24px;
}

.empty-icon iconify-icon {
    font-size: 48px;
    color: var(--muted);
}

.empty-state h3 {
    font-size: 1.25rem;
    font-weight: 700;
    color: var(--text);
    margin-bottom: 8px;
}

.empty-state p {
    color: var(--text-secondary);
    margin-bottom: 24px;
}

/* Modal */
.modal-overlay {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,0.6);
    backdrop-filter: blur(4px);
    z-index: 1000;
    align-items: center;
    justify-content: center;
    padding: 20px;
}

.modal-overlay.active {
    display: flex;
}

.modal {
    background: var(--surface);
    border-radius: var(--radius-lg);
    max-width: 500px;
    width: 100%;
    max-height: 90vh;
    overflow-y: auto;
}

.modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 24px;
    border-bottom: 1px solid var(--border);
}

.modal-header h2 {
    font-size: 1.25rem;
    font-weight: 700;
}

.modal-close {
    width: 36px;
    height: 36px;
    border-radius: var(--radius);
    background: var(--surface-hover);
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--text);
    transition: all 0.2s;
}

.modal-close:hover {
    background: var(--primary);
    color: white;
}

.modal-body {
    padding: 24px;
}

.form-group {
    margin-bottom: 20px;
}

.form-label {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    color: var(--text);
    font-size: 0.9rem;
}

.form-label .required {
    color: #EF4444;
}

.form-input {
    width: 100%;
    padding: 14px;
    border: 1px solid var(--border);
    border-radius: var(--radius);
    font-size: 1rem;
    background: var(--bg);
    color: var(--text);
    transition: border-color 0.2s;
}

.form-input:focus {
    outline: none;
    border-color: var(--primary);
}

.form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
}

.form-checkbox {
    display: flex;
    align-items: center;
    gap: 10px;
    cursor: pointer;
}

.form-checkbox input {
    width: 20px;
    height: 20px;
    accent-color: var(--primary);
}

.modal-footer {
    display: flex;
    gap: 12px;
    padding: 20px 24px;
    border-top: 1px solid var(--border);
}

.btn-modal {
    flex: 1;
    padding: 14px;
    border-radius: var(--radius);
    font-weight: 600;
    font-size: 1rem;
    cursor: pointer;
    transition: all 0.2s;
    border: none;
}

.btn-modal.cancel {
    background: var(--surface-hover);
    color: var(--text);
}

.btn-modal.cancel:hover {
    background: var(--border);
}

.btn-modal.save {
    background: var(--primary);
    color: white;
}

.btn-modal.save:hover {
    background: var(--primary-hover);
}

/* Responsivo - Tablets */
@media (max-width: 992px) {
    .page-container {
        padding: 20px;
    }
    
    .addresses-grid {
        grid-template-columns: 1fr;
    }
}

/* Responsivo - Mobile */
@media (max-width: 768px) {
    .page-container {
        padding: 16px;
    }
    
    .page-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
    }
    
    .page-title {
        font-size: 1.4rem;
    }
    
    .back-link {
        font-size: 0.9rem;
    }
    
    .btn-add-address {
        width: 100%;
        justify-content: center;
        padding: 14px 20px;
    }
    
    .addresses-grid {
        grid-template-columns: 1fr;
        gap: 16px;
    }
    
    .address-card {
        padding: 16px;
    }
    
    .address-label h3 {
        font-size: 1rem;
    }
    
    .address-content {
        font-size: 0.9rem;
    }
    
    .address-actions {
        flex-direction: column;
        gap: 8px;
    }
    
    .btn-action {
        width: 100%;
        justify-content: center;
        padding: 10px;
    }
    
    /* Modal Responsivo */
    .modal-overlay {
        padding: 12px;
        align-items: flex-end;
    }
    
    .modal {
        max-height: 85vh;
        border-radius: var(--radius-lg) var(--radius-lg) 0 0;
    }
    
    .modal-header {
        padding: 16px 20px;
    }
    
    .modal-header h2 {
        font-size: 1.15rem;
    }
    
    .modal-body {
        padding: 20px;
    }
    
    .form-row {
        grid-template-columns: 1fr;
        gap: 0;
    }
    
    .form-group {
        margin-bottom: 16px;
    }
    
    .form-input {
        padding: 12px;
        font-size: 16px; /* Evita zoom no iOS */
    }
    
    .modal-footer {
        flex-direction: column-reverse;
        padding: 16px 20px;
        gap: 10px;
    }
    
    .btn-modal {
        padding: 14px;
    }
    
    .empty-state {
        padding: 48px 16px;
    }
    
    .empty-icon {
        width: 80px;
        height: 80px;
    }
    
    .empty-icon iconify-icon {
        font-size: 36px;
    }
    
    .empty-state h3 {
        font-size: 1.1rem;
    }
}

/* Responsivo - Mobile pequeno */
@media (max-width: 400px) {
    .page-container {
        padding: 12px;
    }
    
    .page-title {
        font-size: 1.2rem;
    }
    
    .address-card {
        padding: 14px;
    }
    
    .badge-default {
        font-size: 0.7rem;
        padding: 3px 8px;
    }
    
    .modal-overlay {
        padding: 8px;
    }
    
    .modal-header,
    .modal-body,
    .modal-footer {
        padding: 14px 16px;
    }
}
</style>
</head>
<body>

<?php include __DIR__ . '/../../../includes/cart.php'; ?>

<?php include __DIR__ . '/includes/header.php'; ?>

<div class="page-container">
    <div class="page-header">
        <h1 class="page-title">
            <iconify-icon icon="solar:map-point-bold"></iconify-icon>
            Meus Endereços
        </h1>
        <a href="<?php echo storeUrl('minha-conta'); ?>" class="back-link">
            <iconify-icon icon="solar:arrow-left-linear"></iconify-icon>
            Voltar para Minha Conta
        </a>
    </div>
    
    <?php if ($message): ?>
    <div class="alert <?php echo $messageType; ?>">
        <iconify-icon icon="<?php echo $messageType === 'success' ? 'solar:check-circle-bold' : 'solar:danger-triangle-bold'; ?>"></iconify-icon>
        <?php echo htmlspecialchars($message); ?>
    </div>
    <?php endif; ?>
    
    <div style="margin-bottom: 24px;">
        <button class="btn-add-address" onclick="openAddressModal()">
            <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
            Adicionar Endereço
        </button>
    </div>
    
    <?php if (empty($addresses)): ?>
    <div class="empty-state">
        <div class="empty-icon">
            <iconify-icon icon="solar:map-point-bold"></iconify-icon>
        </div>
        <h3>Nenhum endereço cadastrado</h3>
        <p>Adicione um endereço para facilitar suas compras.</p>
    </div>
    <?php else: ?>
    <div class="addresses-grid">
        <?php foreach ($addresses as $address): ?>
        <div class="address-card <?php echo $address['is_default'] ? 'default' : ''; ?>">
            <div class="address-label">
                <h3><?php echo htmlspecialchars($address['label'] ?: 'Endereço'); ?></h3>
                <?php if ($address['is_default']): ?>
                <span class="badge-default">Padrão</span>
                <?php endif; ?>
            </div>
            <div class="address-content">
                <strong><?php echo htmlspecialchars($address['street']); ?>, <?php echo htmlspecialchars($address['number']); ?></strong>
                <?php if ($address['complement']): ?>
                    - <?php echo htmlspecialchars($address['complement']); ?>
                <?php endif; ?>
                <br>
                <?php echo htmlspecialchars($address['neighborhood']); ?><br>
                <?php echo htmlspecialchars($address['city']); ?> - <?php echo htmlspecialchars($address['state']); ?><br>
                CEP: <?php echo substr($address['cep'], 0, 5) . '-' . substr($address['cep'], 5); ?>
            </div>
            <div class="address-actions">
                <button class="btn-action edit" onclick='editAddress(<?php echo json_encode($address); ?>)'>
                    <iconify-icon icon="solar:pen-bold"></iconify-icon>
                    Editar
                </button>
                <?php if (!$address['is_default']): ?>
                <form method="POST" style="display: inline;">
                    <input type="hidden" name="action" value="set_default">
                    <input type="hidden" name="address_id" value="<?php echo $address['id']; ?>">
                    <button type="submit" class="btn-action default">
                        <iconify-icon icon="solar:star-bold"></iconify-icon>
                        Tornar Padrão
                    </button>
                </form>
                <form method="POST" style="display: inline;" onsubmit="return confirm('Tem certeza que deseja remover este endereço?')">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="address_id" value="<?php echo $address['id']; ?>">
                    <button type="submit" class="btn-action delete">
                        <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                        Remover
                    </button>
                </form>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

<!-- Address Modal -->
<div class="modal-overlay" id="addressModal">
    <div class="modal">
        <div class="modal-header">
            <h2 id="modalTitle">Novo Endereço</h2>
            <button class="modal-close" onclick="closeAddressModal()">
                <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
            </button>
        </div>
        <form method="POST" id="addressForm">
            <input type="hidden" name="action" value="save">
            <input type="hidden" name="address_id" id="address_id">
            
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label">Apelido do endereço</label>
                    <input type="text" name="label" id="label" class="form-input" placeholder="Ex: Casa, Trabalho">
                </div>
                
                <div class="form-group">
                    <label class="form-label">CEP <span class="required">*</span></label>
                    <input type="text" name="cep" id="cep" class="form-input" placeholder="00000-000" maxlength="9" required onblur="searchCep(this.value)">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Rua <span class="required">*</span></label>
                    <input type="text" name="street" id="street" class="form-input" required>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Número <span class="required">*</span></label>
                        <input type="text" name="number" id="number" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Complemento</label>
                        <input type="text" name="complement" id="complement" class="form-input" placeholder="Apto, Bloco...">
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Bairro <span class="required">*</span></label>
                    <input type="text" name="neighborhood" id="neighborhood" class="form-input" required>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Cidade <span class="required">*</span></label>
                        <input type="text" name="city" id="city" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Estado <span class="required">*</span></label>
                        <select name="state" id="state" class="form-input" required>
                            <option value="">Selecione</option>
                            <?php foreach ($states as $state): ?>
                            <option value="<?php echo $state; ?>"><?php echo $state; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-checkbox">
                        <input type="checkbox" name="is_default" id="is_default">
                        Definir como endereço padrão
                    </label>
                </div>
            </div>
            
            <div class="modal-footer">
                <button type="button" class="btn-modal cancel" onclick="closeAddressModal()">Cancelar</button>
                <button type="submit" class="btn-modal save">Salvar Endereço</button>
            </div>
        </form>
    </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
<script>
function openAddressModal() {
    document.getElementById('modalTitle').textContent = 'Novo Endereço';
    document.getElementById('addressForm').reset();
    document.getElementById('address_id').value = '';
    document.getElementById('addressModal').classList.add('active');
}

function closeAddressModal() {
    document.getElementById('addressModal').classList.remove('active');
}

function editAddress(address) {
    document.getElementById('modalTitle').textContent = 'Editar Endereço';
    document.getElementById('address_id').value = address.id;
    document.getElementById('label').value = address.label || '';
    document.getElementById('cep').value = formatCep(address.cep);
    document.getElementById('street').value = address.street;
    document.getElementById('number').value = address.number;
    document.getElementById('complement').value = address.complement || '';
    document.getElementById('neighborhood').value = address.neighborhood;
    document.getElementById('city').value = address.city;
    document.getElementById('state').value = address.state;
    document.getElementById('is_default').checked = address.is_default == 1;
    document.getElementById('addressModal').classList.add('active');
}

function formatCep(cep) {
    cep = cep.replace(/\D/g, '');
    if (cep.length === 8) {
        return cep.substring(0, 5) + '-' + cep.substring(5);
    }
    return cep;
}

// Formatar CEP ao digitar
document.getElementById('cep').addEventListener('input', function(e) {
    let value = e.target.value.replace(/\D/g, '');
    if (value.length > 5) {
        value = value.substring(0, 5) + '-' + value.substring(5, 8);
    }
    e.target.value = value;
});

// Buscar CEP
async function searchCep(cep) {
    cep = cep.replace(/\D/g, '');
    if (cep.length !== 8) return;
    
    try {
        const response = await fetch(`https://viacep.com.br/ws/${cep}/json/`);
        const data = await response.json();
        
        if (!data.erro) {
            document.getElementById('street').value = data.logradouro;
            document.getElementById('neighborhood').value = data.bairro;
            document.getElementById('city').value = data.localidade;
            document.getElementById('state').value = data.uf;
            document.getElementById('number').focus();
        }
    } catch (error) {
        console.error('Erro ao buscar CEP:', error);
    }
}

// Fechar modal ao clicar fora
document.getElementById('addressModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeAddressModal();
    }
});
</script>

</body>
</html>
