<?php
$pageTitle = "Meu Perfil - CATÁLOGO 44";
include 'header.php';
include '../adm/config/db.php';

// Segurança: Verificar login
if (!isset($_SESSION['usuario_id'])) {
    echo "<script>window.location.href='login.php';</script>";
    exit;
}

$uId = $_SESSION['usuario_id'];
$mensagem = '';
$erro = '';

// Se o formulário for enviado
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nome = $_POST['nome_completo'];
    $email = $_POST['email_principal'];
    $cpf_cnpj = preg_replace('/\D/', '', $_POST['cpf_cnpj']);
    $ponto_referencia = $_POST['ponto_referencia'];
    
    // Dados de endereço
    $cep = $_POST['cep'] ?? '';
    $endereco = $_POST['endereco'] ?? '';
    $numero = $_POST['numero'] ?? '';
    $complemento = $_POST['complemento'] ?? '';
    $bairro = $_POST['bairro'] ?? '';
    $cidade = $_POST['cidade'] ?? '';
    $estado = $_POST['estado'] ?? '';

    $stmt = $conn->prepare("UPDATE usuarios SET nome_completo=?, email_principal=?, cpf_cnpj=?, ponto_referencia=?, cep=?, endereco=?, numero=?, complemento=?, bairro=?, cidade=?, estado=? WHERE id=?");
    $stmt->bind_param("sssssssssssi", $nome, $email, $cpf_cnpj, $ponto_referencia, $cep, $endereco, $numero, $complemento, $bairro, $cidade, $estado, $uId);
    
    if ($stmt->execute()) {
        $mensagem = "Cadastro atualizado com sucesso!";
        $_SESSION['usuario_nome'] = $nome; // Atualiza nome na sessão
    } else {
        $erro = "Erro ao atualizar: " . $conn->error;
    }
}

// Buscar dados atuais
$stmt = $conn->prepare("SELECT * FROM usuarios WHERE id = ?");
$stmt->bind_param("i", $uId);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
?>

    <!-- Hero Start -->
    <div class="container-fluid bg-primary py-5 hero-header mb-5">
        <div class="row py-3">
            <div class="col-12 text-center">
                <h1 class="display-3 text-white animated zoomIn">Meu Perfil</h1>
                <a href="index.php" class="h4 text-white">Início</a>
                <i class="far fa-circle text-white px-2"></i>
                <span class="h4 text-white">Editar Cadastro</span>
            </div>
        </div>
    </div>
    <!-- Hero End -->

    <div class="container-fluid py-5">
        <div class="container">
            <div class="row g-5 justify-content-center">
                <div class="col-lg-8 wow slideInUp" data-wow-delay="0.1s">
                    <div class="bg-light rounded p-5 shadow">
                        <div class="section-title mb-4">
                            <h5 class="position-relative d-inline-block text-primary text-uppercase">Configurações</h5>
                            <h1 class="display-6 mb-0">Seus Dados Pessoais</h1>
                        </div>

                        <?php if ($mensagem): ?>
                            <div class="alert alert-success border-0 mb-4"><?= $mensagem ?></div>
                        <?php endif; ?>
                        <?php if ($erro): ?>
                            <div class="alert alert-danger border-0 mb-4"><?= $erro ?></div>
                        <?php endif; ?>

                        <form action="perfil.php" method="POST">
                            <div class="row g-3">
                                <div class="col-md-12">
                                    <label class="form-label">Nome Completo</label>
                                    <input type="text" name="nome_completo" class="form-control border-0 bg-white px-4" style="height: 55px;" value="<?= htmlspecialchars($user['nome_completo']) ?>" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">E-mail</label>
                                    <input type="email" name="email_principal" class="form-control border-0 bg-white px-4" style="height: 55px;" value="<?= htmlspecialchars($user['email_principal']) ?>" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">CPF / CNPJ</label>
                                    <input type="text" id="input_cpf_cnpj" name="cpf_cnpj" class="form-control border-0 bg-white px-4" style="height: 55px;" value="<?= htmlspecialchars($user['cpf_cnpj']) ?>" required>
                                </div>
                                <div class="col-md-12">
                                    <label class="form-label">Observação / Ponto de Referência</label>
                                    <input type="text" name="ponto_referencia" class="form-control border-0 bg-white px-4" placeholder="Ex: Próximo ao mercado X" style="height: 55px;" value="<?= htmlspecialchars($user['ponto_referencia'] ?? '') ?>">
                                </div>

                                <!-- SEÇÃO DE ENDEREÇO OCULTA -->
                                <div class="col-12 mt-4">
                                    <div class="form-check form-switch p-0 ms-4">
                                        <input class="form-check-input" type="checkbox" id="toggleAddress" style="cursor:pointer;">
                                        <label class="form-check-label fw-bold ms-2" for="toggleAddress" style="cursor:pointer;">Desejo alterar meu endereço de entrega</label>
                                    </div>
                                </div>

                                <div id="addressFields" style="display: none;" class="row g-3 mt-1">
                                    <div class="col-md-4">
                                        <label class="form-label text-primary small fw-bold">CEP</label>
                                        <input type="text" name="cep" id="cep" class="form-control border-0 bg-white px-4" style="height: 55px;" value="<?= htmlspecialchars($user['cep'] ?? '') ?>">
                                    </div>
                                    <div class="col-md-8">
                                        <label class="form-label text-primary small fw-bold">Rua / Logradouro</label>
                                        <input type="text" name="endereco" id="rua" class="form-control border-0 bg-white px-4" style="height: 55px;" value="<?= htmlspecialchars($user['endereco'] ?? '') ?>">
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label text-primary small fw-bold">Número</label>
                                        <input type="text" name="numero" class="form-control border-0 bg-white px-4" style="height: 55px;" value="<?= htmlspecialchars($user['numero'] ?? '') ?>">
                                    </div>
                                    <div class="col-md-9">
                                        <label class="form-label text-primary small fw-bold">Complemento</label>
                                        <input type="text" name="complemento" class="form-control border-0 bg-white px-4" style="height: 55px;" value="<?= htmlspecialchars($user['complemento'] ?? '') ?>">
                                    </div>
                                    <div class="col-md-5">
                                        <label class="form-label text-primary small fw-bold">Bairro</label>
                                        <input type="text" name="bairro" id="bairro" class="form-control border-0 bg-white px-4" style="height: 55px;" value="<?= htmlspecialchars($user['bairro'] ?? '') ?>">
                                    </div>
                                    <div class="col-md-5">
                                        <label class="form-label text-primary small fw-bold">Cidade</label>
                                        <input type="text" name="cidade" id="cidade" class="form-control border-0 bg-white px-4" style="height: 55px;" value="<?= htmlspecialchars($user['cidade'] ?? '') ?>">
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label text-primary small fw-bold">UF</label>
                                        <input type="text" name="estado" id="uf" class="form-control border-0 bg-white px-4" style="height: 55px;" value="<?= htmlspecialchars($user['estado'] ?? '') ?>">
                                    </div>
                                </div>

                                <div class="col-12 mt-5">
                                    <button class="btn btn-primary w-100 py-3" type="submit">SALVAR ALTERAÇÕES</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
    // Toggle para mostrar/esconder campos de endereço
    const toggle = document.getElementById('toggleAddress');
    const fields = document.getElementById('addressFields');
    toggle.addEventListener('change', () => {
        fields.style.display = toggle.checked ? 'flex' : 'none';
        if(toggle.checked) {
            document.getElementById('cep').scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
    });

    // Máscara CPF/CNPJ (Dinâmica)
    document.getElementById('input_cpf_cnpj').addEventListener('input', function(e) {
        let value = e.target.value.replace(/\D/g, '');
        if (value.length <= 11) {
            value = value.replace(/(\d{3})(\d)/, '$1.$2');
            value = value.replace(/(\d{3})(\d)/, '$1.$2');
            value = value.replace(/(\d{3})(\d{1,2})$/, '$1-$2');
        } else {
            value = value.slice(0, 14);
            value = value.replace(/^(\d{2})(\d)/, '$1.$2');
            value = value.replace(/^(\d{2})\.(\d{3})(\d)/, '$1.$2.$3');
            value = value.replace(/\.(\d{3})(\d)/, '.$1/$2');
            value = value.replace(/(\d{4})(\d)/, '$1-$2');
        }
        e.target.value = value;
    });

    // CEP API
    const inputCep = document.getElementById('cep');
    inputCep.addEventListener('input', function(e) {
        let v = e.target.value.replace(/\D/g, '');
        v = v.replace(/^(\d{5})(\d)/, '$1-$2').slice(0, 9);
        e.target.value = v;

        if (v.length === 9) {
            let cepNum = v.replace('-', '');
            fetch(`https://viacep.com.br/ws/${cepNum}/json/`)
                .then(r => r.json())
                .then(data => {
                    if (!data.erro) {
                        document.getElementById('rua').value = data.logradouro;
                        document.getElementById('bairro').value = data.bairro;
                        document.getElementById('cidade').value = data.localidade;
                        document.getElementById('uf').value = data.uf;
                    }
                });
        }
    });
    </script>

<?php 
$marginTop = 'style="margin-top: -75px;"'; 
include 'footer.php'; 
?>
