<?php
/**
 * Alterar Senha - MontaLoja
 * Página para alteração de senha do cliente
 */

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

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

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

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

// Processar alteração de senha
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $currentPassword = $_POST['current_password'] ?? '';
    $newPassword = $_POST['new_password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';
    
    if (empty($currentPassword) || empty($newPassword) || empty($confirmPassword)) {
        $message = 'Preencha todos os campos.';
        $messageType = 'error';
    } elseif ($newPassword !== $confirmPassword) {
        $message = 'A nova senha e a confirmação não coincidem.';
        $messageType = 'error';
    } elseif (strlen($newPassword) < 6) {
        $message = 'A nova senha deve ter pelo menos 6 caracteres.';
        $messageType = 'error';
    } else {
        // Buscar senha atual
        $stmt = $pdo->prepare("SELECT password FROM customers WHERE id = ?");
        $stmt->execute([$customerId]);
        $customerData = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!password_verify($currentPassword, $customerData['password'])) {
            $message = 'Senha atual incorreta.';
            $messageType = 'error';
        } else {
            try {
                $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("UPDATE customers SET password = ? WHERE id = ?");
                $stmt->execute([$hashedPassword, $customerId]);
                
                // PRG Pattern - Redirecionar após sucesso
                $_SESSION['flash_message'] = 'Senha alterada com sucesso!';
                $_SESSION['flash_type'] = 'success';
                header("Location: " . storeUrl('alterar-senha'));
                exit;
            } catch (Exception $e) {
                $message = 'Erro ao alterar senha. 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>Alterar Senha - <?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: 500px;
    margin: 0 auto;
    padding: 24px;
}

.page-header {
    text-align: center;
    margin-bottom: 32px;
}

.page-icon {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background: linear-gradient(135deg, var(--primary), var(--primary-hover));
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 20px;
}

.page-icon iconify-icon {
    font-size: 40px;
    color: white;
}

.page-title {
    font-size: 1.75rem;
    font-weight: 800;
    color: var(--text);
    margin-bottom: 8px;
}

.page-subtitle {
    color: var(--text-secondary);
    font-size: 1rem;
}

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

.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);
}

/* Form Card */
.form-card {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: var(--radius-lg);
    padding: 32px;
}

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

.form-group:last-of-type {
    margin-bottom: 32px;
}

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

.input-wrapper {
    position: relative;
}

.form-input {
    width: 100%;
    padding: 14px 48px 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);
}

.toggle-password {
    position: absolute;
    right: 14px;
    top: 50%;
    transform: translateY(-50%);
    background: none;
    border: none;
    cursor: pointer;
    color: var(--text-muted);
    padding: 4px;
    transition: color 0.2s;
}

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

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

/* Password Strength */
.password-strength {
    margin-top: 12px;
}

.strength-bar {
    height: 4px;
    background: var(--border);
    border-radius: 2px;
    overflow: hidden;
    margin-bottom: 8px;
}

.strength-fill {
    height: 100%;
    width: 0%;
    transition: all 0.3s;
    border-radius: 2px;
}

.strength-fill.weak { width: 33%; background: #EF4444; }
.strength-fill.medium { width: 66%; background: #F59E0B; }
.strength-fill.strong { width: 100%; background: #10B981; }

.strength-text {
    font-size: 0.85rem;
    font-weight: 500;
}

.strength-text.weak { color: #EF4444; }
.strength-text.medium { color: #F59E0B; }
.strength-text.strong { color: #10B981; }

.btn-submit {
    width: 100%;
    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-submit:hover {
    background: var(--primary-hover);
    transform: translateY(-2px);
}

.btn-submit:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none;
}

/* Security Tips */
.security-tips {
    margin-top: 24px;
    padding: 20px;
    background: var(--surface-hover);
    border-radius: var(--radius);
}

.security-tips h4 {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 0.95rem;
    font-weight: 700;
    color: var(--text);
    margin-bottom: 12px;
}

.security-tips iconify-icon {
    color: var(--primary);
}

.security-tips ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

.security-tips li {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    font-size: 0.9rem;
    color: var(--text-secondary);
    margin-bottom: 8px;
}

.security-tips li:last-child {
    margin-bottom: 0;
}

.security-tips li iconify-icon {
    color: var(--primary);
    margin-top: 2px;
    flex-shrink: 0;
}

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

/* Responsivo - Mobile */
@media (max-width: 768px) {
    .page-container {
        padding: 16px;
        max-width: 100%;
    }
    
    .page-header {
        margin-bottom: 24px;
    }
    
    .page-icon {
        width: 64px;
        height: 64px;
        margin-bottom: 16px;
    }
    
    .page-icon iconify-icon {
        font-size: 32px;
    }
    
    .page-title {
        font-size: 1.4rem;
    }
    
    .page-subtitle {
        font-size: 0.9rem;
    }
    
    .back-link {
        font-size: 0.9rem;
        margin-top: 12px;
    }
    
    .alert {
        padding: 12px;
        font-size: 0.9rem;
    }
    
    .form-card {
        padding: 20px;
    }
    
    .form-group {
        margin-bottom: 20px;
    }
    
    .form-label {
        font-size: 0.85rem;
    }
    
    .form-input {
        padding: 12px 44px 12px 14px;
        font-size: 16px; /* Evita zoom no iOS */
    }
    
    .toggle-password {
        right: 12px;
    }
    
    .form-hint {
        font-size: 0.8rem;
        margin-top: 6px;
    }
    
    .password-strength {
        margin-top: 10px;
    }
    
    .strength-text {
        font-size: 0.8rem;
    }
    
    .btn-submit {
        padding: 14px;
        font-size: 0.95rem;
    }
    
    .security-tips {
        padding: 16px;
        margin-top: 20px;
    }
    
    .security-tips h4 {
        font-size: 0.9rem;
    }
    
    .security-tips li {
        font-size: 0.85rem;
    }
}

/* Responsivo - Mobile pequeno */
@media (max-width: 400px) {
    .page-container {
        padding: 12px;
    }
    
    .page-icon {
        width: 56px;
        height: 56px;
    }
    
    .page-icon iconify-icon {
        font-size: 28px;
    }
    
    .page-title {
        font-size: 1.2rem;
    }
    
    .form-card {
        padding: 16px;
    }
    
    .form-group:last-of-type {
        margin-bottom: 24px;
    }
    
    .security-tips {
        padding: 14px;
    }
    
    .security-tips li {
        font-size: 0.8rem;
    }
}
</style>
</head>
<body>

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

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

<div class="page-container">
    <div class="page-header">
        <div class="page-icon">
            <iconify-icon icon="solar:lock-password-bold"></iconify-icon>
        </div>
        <h1 class="page-title">Alterar Senha</h1>
        <p class="page-subtitle">Mantenha sua conta segura atualizando sua senha regularmente.</p>
        <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="form-card">
        <form method="POST" id="passwordForm">
            <div class="form-group">
                <label class="form-label">Senha Atual</label>
                <div class="input-wrapper">
                    <input type="password" name="current_password" id="current_password" class="form-input" required>
                    <button type="button" class="toggle-password" onclick="togglePassword('current_password')">
                        <iconify-icon icon="solar:eye-bold" width="20"></iconify-icon>
                    </button>
                </div>
            </div>
            
            <div class="form-group">
                <label class="form-label">Nova Senha</label>
                <div class="input-wrapper">
                    <input type="password" name="new_password" id="new_password" class="form-input" required oninput="checkPasswordStrength(this.value)">
                    <button type="button" class="toggle-password" onclick="togglePassword('new_password')">
                        <iconify-icon icon="solar:eye-bold" width="20"></iconify-icon>
                    </button>
                </div>
                <div class="password-strength" id="passwordStrength" style="display: none;">
                    <div class="strength-bar">
                        <div class="strength-fill" id="strengthFill"></div>
                    </div>
                    <span class="strength-text" id="strengthText"></span>
                </div>
                <p class="form-hint">Mínimo de 6 caracteres.</p>
            </div>
            
            <div class="form-group">
                <label class="form-label">Confirmar Nova Senha</label>
                <div class="input-wrapper">
                    <input type="password" name="confirm_password" id="confirm_password" class="form-input" required oninput="checkPasswordMatch()">
                    <button type="button" class="toggle-password" onclick="togglePassword('confirm_password')">
                        <iconify-icon icon="solar:eye-bold" width="20"></iconify-icon>
                    </button>
                </div>
                <p class="form-hint" id="matchHint" style="display: none;"></p>
            </div>
            
            <button type="submit" class="btn-submit" id="submitBtn">
                <iconify-icon icon="solar:lock-password-bold"></iconify-icon>
                Alterar Senha
            </button>
        </form>
        
        <div class="security-tips">
            <h4>
                <iconify-icon icon="solar:shield-check-bold"></iconify-icon>
                Dicas de Segurança
            </h4>
            <ul>
                <li>
                    <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                    Use pelo menos 8 caracteres
                </li>
                <li>
                    <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                    Combine letras maiúsculas, minúsculas e números
                </li>
                <li>
                    <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                    Evite senhas óbvias como datas de nascimento
                </li>
                <li>
                    <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                    Não reutilize senhas de outros sites
                </li>
            </ul>
        </div>
    </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
<script>
function togglePassword(inputId) {
    const input = document.getElementById(inputId);
    const button = input.parentElement.querySelector('.toggle-password iconify-icon');
    
    if (input.type === 'password') {
        input.type = 'text';
        button.setAttribute('icon', 'solar:eye-closed-bold');
    } else {
        input.type = 'password';
        button.setAttribute('icon', 'solar:eye-bold');
    }
}

function checkPasswordStrength(password) {
    const strengthDiv = document.getElementById('passwordStrength');
    const fill = document.getElementById('strengthFill');
    const text = document.getElementById('strengthText');
    
    if (password.length === 0) {
        strengthDiv.style.display = 'none';
        return;
    }
    
    strengthDiv.style.display = 'block';
    
    let strength = 0;
    
    // Comprimento
    if (password.length >= 6) strength++;
    if (password.length >= 10) strength++;
    
    // Caracteres variados
    if (/[A-Z]/.test(password)) strength++;
    if (/[a-z]/.test(password)) strength++;
    if (/[0-9]/.test(password)) strength++;
    if (/[^A-Za-z0-9]/.test(password)) strength++;
    
    fill.className = 'strength-fill';
    text.className = 'strength-text';
    
    if (strength <= 2) {
        fill.classList.add('weak');
        text.classList.add('weak');
        text.textContent = 'Fraca';
    } else if (strength <= 4) {
        fill.classList.add('medium');
        text.classList.add('medium');
        text.textContent = 'Média';
    } else {
        fill.classList.add('strong');
        text.classList.add('strong');
        text.textContent = 'Forte';
    }
}

function checkPasswordMatch() {
    const newPassword = document.getElementById('new_password').value;
    const confirmPassword = document.getElementById('confirm_password').value;
    const hint = document.getElementById('matchHint');
    
    if (confirmPassword.length === 0) {
        hint.style.display = 'none';
        return;
    }
    
    hint.style.display = 'block';
    
    if (newPassword === confirmPassword) {
        hint.textContent = '✓ Senhas coincidem';
        hint.style.color = '#10B981';
    } else {
        hint.textContent = '✗ Senhas não coincidem';
        hint.style.color = '#EF4444';
    }
}
</script>

</body>
</html>
