<?php
/**
 * Meus Dados - MontaLoja
 * Edição de dados pessoais do cliente
 */

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

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

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

$message = '';
$messageType = '';

// Processar atualização
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = preg_replace('/[^0-9]/', '', $_POST['phone'] ?? '');
    $cpf = preg_replace('/[^0-9]/', '', $_POST['cpf'] ?? '');
    $birthdate = $_POST['birthdate'] ?? null;
    
    if (empty($name) || empty($email)) {
        $message = 'Nome e e-mail são obrigatórios.';
        $messageType = 'error';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $message = 'E-mail inválido.';
        $messageType = 'error';
    } else {
        // Verificar se email já existe (exceto o próprio)
        $stmt = $pdo->prepare("SELECT id FROM customers WHERE email = ? AND store_id = ? AND id != ?");
        $stmt->execute([$email, $currentStoreId, $customerId]);
        if ($stmt->fetch()) {
            $message = 'Este e-mail já está sendo usado por outra conta.';
            $messageType = 'error';
        } else {
            try {
                $stmt = $pdo->prepare("UPDATE customers SET name = ?, email = ?, phone = ?, cpf = ?, birthdate = ? WHERE id = ?");
                $stmt->execute([$name, $email, $phone ?: null, $cpf ?: null, $birthdate ?: null, $customerId]);
                
                // Atualizar sessão
                $_SESSION['customer_name'] = $name;
                $_SESSION['customer_email'] = $email;
                
                // Buscar dados atualizados
                $stmt = $pdo->prepare("SELECT * FROM customers WHERE id = ?");
                $stmt->execute([$customerId]);
                $customer = $stmt->fetch(PDO::FETCH_ASSOC);
                
                // PRG Pattern - Redirecionar após sucesso
                $_SESSION['flash_message'] = 'Dados atualizados com sucesso!';
                $_SESSION['flash_type'] = 'success';
                header("Location: " . storeUrl('meus-dados'));
                exit;
            } catch (Exception $e) {
                $message = 'Erro ao atualizar dados. Tente novamente.';
                $messageType = 'error';
            }
        }
    }
}

// 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']);
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Meus Dados - <?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: 700px;
    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);
}

/* Profile Card */
.profile-card {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: var(--radius-lg);
    overflow: hidden;
}

.profile-header {
    background: linear-gradient(135deg, var(--primary), var(--primary-hover));
    padding: 32px;
    text-align: center;
    position: relative;
}

.profile-avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background: white;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 16px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.profile-avatar iconify-icon {
    font-size: 50px;
    color: var(--primary);
}

.profile-header h2 {
    color: white;
    font-size: 1.5rem;
    font-weight: 700;
    margin-bottom: 4px;
}

.profile-header p {
    color: rgba(255,255,255,0.8);
    font-size: 0.95rem;
}

.profile-body {
    padding: 32px;
}

.form-section {
    margin-bottom: 32px;
}

.form-section:last-child {
    margin-bottom: 0;
}

.form-section-title {
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 1.1rem;
    font-weight: 700;
    color: var(--text);
    margin-bottom: 20px;
    padding-bottom: 12px;
    border-bottom: 1px solid var(--border);
}

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

.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 16px;
    border: 1px solid var(--border);
    border-radius: var(--radius);
    font-size: 1rem;
    background: var(--bg);
    color: var(--text);
    transition: all 0.2s;
}

.form-input:focus {
    outline: none;
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(var(--primary-rgb), 0.1);
}

.form-input:disabled {
    background: var(--surface-hover);
    cursor: not-allowed;
}

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

.form-hint {
    font-size: 0.85rem;
    color: var(--text-muted);
    margin-top: 6px;
}

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

.btn-save {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 16px;
    background: var(--primary);
    color: white;
    border: none;
    border-radius: var(--radius);
    font-weight: 600;
    font-size: 1rem;
    cursor: pointer;
    transition: all 0.2s;
}

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

.btn-password {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 16px 24px;
    background: var(--surface-hover);
    color: var(--text);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    font-weight: 600;
    font-size: 1rem;
    text-decoration: none;
    transition: all 0.2s;
}

.btn-password:hover {
    border-color: var(--primary);
    color: var(--primary);
}

/* Account Info */
.account-info {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 16px;
    background: var(--surface-hover);
    border-radius: var(--radius);
    margin-top: 24px;
}

.account-info iconify-icon {
    font-size: 24px;
    color: var(--primary);
}

.account-info-content p {
    font-size: 0.9rem;
    color: var(--text-secondary);
}

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

/* Responsivo - Tablets */
@media (max-width: 992px) {
    .page-container {
        padding: 20px;
    }
    
    .profile-body {
        padding: 24px;
    }
}

/* 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;
    }
    
    .alert {
        padding: 12px;
        font-size: 0.9rem;
    }
    
    .profile-header {
        padding: 24px 16px;
    }
    
    .profile-avatar {
        width: 80px;
        height: 80px;
    }
    
    .profile-avatar iconify-icon {
        font-size: 40px;
    }
    
    .profile-header h2 {
        font-size: 1.25rem;
    }
    
    .profile-header p {
        font-size: 0.9rem;
    }
    
    .profile-body {
        padding: 20px 16px;
    }
    
    .form-section {
        margin-bottom: 24px;
    }
    
    .form-section-title {
        font-size: 1rem;
    }
    
    .form-row {
        grid-template-columns: 1fr;
        gap: 0;
    }
    
    .form-group {
        margin-bottom: 16px;
    }
    
    .form-label {
        font-size: 0.85rem;
    }
    
    .form-input {
        padding: 12px;
        font-size: 16px; /* Evita zoom no iOS */
    }
    
    .form-hint {
        font-size: 0.8rem;
    }
    
    .form-actions {
        flex-direction: column;
        gap: 10px;
        padding-top: 20px;
    }
    
    .btn-save,
    .btn-password {
        padding: 14px;
        font-size: 0.95rem;
        justify-content: center;
        width: 100%;
    }
    
    .account-info {
        flex-direction: column;
        text-align: center;
        gap: 12px;
        padding: 14px;
    }
    
    .account-info-content p {
        font-size: 0.85rem;
    }
}

/* Responsivo - Mobile pequeno */
@media (max-width: 400px) {
    .page-container {
        padding: 12px;
    }
    
    .page-title {
        font-size: 1.2rem;
    }
    
    .profile-header {
        padding: 20px 12px;
    }
    
    .profile-avatar {
        width: 64px;
        height: 64px;
    }
    
    .profile-avatar iconify-icon {
        font-size: 32px;
    }
    
    .profile-body {
        padding: 16px 12px;
    }
    
    .form-section-title {
        font-size: 0.95rem;
        padding-bottom: 10px;
    }
}
</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:user-bold"></iconify-icon>
            Meus Dados
        </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 class="profile-card">
        <div class="profile-header">
            <div class="profile-avatar">
                <iconify-icon icon="solar:user-bold"></iconify-icon>
            </div>
            <h2><?php echo htmlspecialchars($customer['name']); ?></h2>
            <p><?php echo htmlspecialchars($customer['email']); ?></p>
        </div>
        
        <div class="profile-body">
            <form method="POST">
                <div class="form-section">
                    <h3 class="form-section-title">
                        <iconify-icon icon="solar:user-id-bold"></iconify-icon>
                        Informações Pessoais
                    </h3>
                    
                    <div class="form-group">
                        <label class="form-label">Nome Completo <span class="required">*</span></label>
                        <input type="text" name="name" class="form-input" value="<?php echo htmlspecialchars($customer['name']); ?>" required>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">CPF</label>
                            <input type="text" name="cpf" id="cpf" class="form-input" value="<?php echo formatCpf($customer['cpf'] ?? ''); ?>" placeholder="000.000.000-00">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Data de Nascimento</label>
                            <input type="date" name="birthdate" class="form-input" value="<?php echo $customer['birthdate'] ?? ''; ?>">
                        </div>
                    </div>
                </div>
                
                <div class="form-section">
                    <h3 class="form-section-title">
                        <iconify-icon icon="solar:phone-bold"></iconify-icon>
                        Contato
                    </h3>
                    
                    <div class="form-group">
                        <label class="form-label">E-mail <span class="required">*</span></label>
                        <input type="email" name="email" class="form-input" value="<?php echo htmlspecialchars($customer['email']); ?>" required>
                        <p class="form-hint">Usado para login e receber atualizações dos seus pedidos.</p>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Telefone</label>
                        <input type="text" name="phone" id="phone" class="form-input" value="<?php echo formatPhone($customer['phone'] ?? ''); ?>" placeholder="(00) 00000-0000">
                    </div>
                </div>
                
                <div class="form-actions">
                    <button type="submit" class="btn-save">
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                        Salvar Alterações
                    </button>
                    <a href="<?php echo storeUrl('alterar-senha'); ?>" class="btn-password">
                        <iconify-icon icon="solar:lock-password-bold"></iconify-icon>
                        Alterar Senha
                    </a>
                </div>
            </form>
            
            <div class="account-info">
                <iconify-icon icon="solar:info-circle-bold"></iconify-icon>
                <div class="account-info-content">
                    <p>Conta criada em <strong><?php echo date('d/m/Y', strtotime($customer['created_at'])); ?></strong></p>
                    <?php if (!empty($customer['last_login'])): ?>
                    <p>Último acesso: <strong><?php echo date('d/m/Y \à\s H:i', strtotime($customer['last_login'])); ?></strong></p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
<script>
// Formatação de CPF
document.getElementById('cpf').addEventListener('input', function(e) {
    let value = e.target.value.replace(/\D/g, '');
    if (value.length > 11) value = value.substring(0, 11);
    
    if (value.length > 9) {
        value = value.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4');
    } else if (value.length > 6) {
        value = value.replace(/(\d{3})(\d{3})(\d{1,3})/, '$1.$2.$3');
    } else if (value.length > 3) {
        value = value.replace(/(\d{3})(\d{1,3})/, '$1.$2');
    }
    
    e.target.value = value;
});

// Formatação de telefone
document.getElementById('phone').addEventListener('input', function(e) {
    let value = e.target.value.replace(/\D/g, '');
    if (value.length > 11) value = value.substring(0, 11);
    
    if (value.length > 10) {
        value = value.replace(/(\d{2})(\d{5})(\d{4})/, '($1) $2-$3');
    } else if (value.length > 6) {
        value = value.replace(/(\d{2})(\d{4,5})(\d{0,4})/, '($1) $2-$3');
    } else if (value.length > 2) {
        value = value.replace(/(\d{2})(\d{0,5})/, '($1) $2');
    }
    
    e.target.value = value;
});
</script>

</body>
</html>
<?php
// Funções auxiliares
function formatCpf($cpf) {
    $cpf = preg_replace('/[^0-9]/', '', $cpf);
    if (strlen($cpf) === 11) {
        return substr($cpf, 0, 3) . '.' . substr($cpf, 3, 3) . '.' . substr($cpf, 6, 3) . '-' . substr($cpf, 9, 2);
    }
    return $cpf;
}

function formatPhone($phone) {
    $phone = preg_replace('/[^0-9]/', '', $phone);
    if (strlen($phone) === 11) {
        return '(' . substr($phone, 0, 2) . ') ' . substr($phone, 2, 5) . '-' . substr($phone, 7);
    } elseif (strlen($phone) === 10) {
        return '(' . substr($phone, 0, 2) . ') ' . substr($phone, 2, 4) . '-' . substr($phone, 6);
    }
    return $phone;
}
?>
