feat(auth-firebase): implement Phase 2 integration - Firebase Auth, Session Sync, Favorites Grid, and Firestore Newsletter

This commit is contained in:
2026-05-21 14:14:10 +02:00
parent 548c7605bc
commit 21833fa05b
15 changed files with 1532 additions and 40 deletions
+682
View File
@@ -0,0 +1,682 @@
<?php
require __DIR__ . '/helpers.php';
$lang = (isset($_GET['lang']) && strtolower($_GET['lang']) === 'de') ? 'de' : 'en';
$copy = [
'en' => [
'page_title' => 'My Profile & Favorites | FlixCooks',
'meta_desc' => 'Manage your profile, dietary goals, and saved seasonal recipes on FlixCooks.',
'login' => 'Login',
'signup' => 'Register',
'email' => 'Email Address',
'password' => 'Password',
'confirm_pass' => 'Confirm Password',
'goal' => 'Dietary Goal',
'goal_placeholder' => 'Select your dietary goal',
'goal_loose' => 'Weight Loss / Low-Carb',
'goal_gain' => 'Muscle Gain / High-Protein',
'goal_healthy' => 'Healthy & Balanced',
'no_account' => "Don't have an account yet?",
'have_account' => 'Already have an account?',
'welcome' => 'Welcome back,',
'your_goal' => 'Your dietary goal',
'saved_recipes' => 'Your Saved Favorites',
'no_favorites' => "You haven't saved any recipes yet. Explore our collection and tap the heart icon!",
'logout' => 'Log Out',
'err_pass_match' => 'Passwords do not match.',
'err_fill_fields'=> 'Please fill in all fields.',
],
'de' => [
'page_title' => 'Mein Profil & Favoriten | FlixCooks',
'meta_desc' => 'Verwalte dein Profil, deine Ernährungsziele und gespeicherten Rezepte auf FlixCooks.',
'login' => 'Anmelden',
'signup' => 'Registrieren',
'email' => 'E-Mail-Adresse',
'password' => 'Passwort',
'confirm_pass' => 'Passwort bestätigen',
'goal' => 'Ernährungsziel',
'goal_placeholder' => 'Wähle dein Ernährungsziel',
'goal_loose' => 'Abnehmen / Low-Carb',
'goal_gain' => 'Muskelaufbau / High-Protein',
'goal_healthy' => 'Gesund & Ausgewogen',
'no_account' => "Noch kein Konto?",
'have_account' => 'Bereits registriert?',
'welcome' => 'Willkommen zurück,',
'your_goal' => 'Dein Ernährungsziel',
'saved_recipes' => 'Deine gespeicherten Favoriten',
'no_favorites' => "Du hast noch keine Rezepte gespeichert. Entdecke unsere Küche und klicke auf das Herz-Symbol!",
'logout' => 'Abmelden',
'err_pass_match' => 'Die Passwörter stimmen nicht überein.',
'err_fill_fields'=> 'Bitte fülle alle Felder aus.',
]
];
$t = $copy[$lang];
$pageTitle = $t['page_title'];
$description = $t['meta_desc'];
// Check PHP session state
$user = $_SESSION['fc_user'] ?? null;
$allRecipes = load_recipes();
$allRecipesLocal = localize_recipes($allRecipes, $lang);
// Formatter helper for JS usage
$recipesJson = json_encode(array_values(array_map(function($r) use ($lang) {
return [
'slug' => $r['slug'],
'title' => $r['title'],
'hero' => $r['hero'],
'difficulty' => $r['difficulty'],
'total_time' => (int)($r['total_time'] ?? 0),
'url' => '/recipe.php?slug=' . urlencode($r['slug']) . '&lang=' . $lang
];
}, $allRecipesLocal)));
include __DIR__ . '/partials/head.php';
include __DIR__ . '/partials/header.php';
?>
<style>
/* ── Premium Authentication Page Styling ── */
.auth-page {
padding: clamp(6rem, 10vh, 10rem) var(--grid-margin) clamp(4rem, 8vh, 6rem);
min-height: 80vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.auth-card {
width: 100%;
max-width: 500px;
background: var(--surface-2);
border: 1px solid var(--stroke);
box-shadow: var(--shadow);
border-radius: var(--radius);
padding: clamp(2rem, 5vw, 3.5rem);
position: relative;
overflow: hidden;
transition: transform 0.4s var(--ease-out-expo), opacity 0.4s ease;
}
.auth-tabs {
display: flex;
justify-content: center;
gap: 2rem;
margin-bottom: 2.5rem;
border-bottom: 1px solid var(--stroke);
padding-bottom: 0.8rem;
}
.auth-tab {
font-family: var(--font-serif-display);
font-size: 1.5rem;
color: var(--color-text-muted);
background: none;
border: none;
cursor: pointer;
padding: 0;
position: relative;
transition: color 0.3s ease;
}
.auth-tab.active {
color: var(--ink);
}
.auth-tab::after {
content: '';
position: absolute;
bottom: -0.9rem;
left: 0;
width: 100%;
height: 2px;
background-color: var(--color-accent-gold);
transform: scaleX(0);
transform-origin: center;
transition: transform 0.4s var(--ease-out-expo);
}
.auth-tab.active::after {
transform: scaleX(1);
}
.auth-form {
display: none;
flex-direction: column;
gap: 1.5rem;
}
.auth-form.active {
display: flex;
animation: authFadeIn 0.5s var(--ease-out-expo) both;
}
@keyframes authFadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
.auth-field {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.auth-field label {
font-family: var(--font-sans-clean);
font-size: 0.8rem;
text-transform: uppercase;
letter-spacing: 0.08em;
font-weight: 700;
color: var(--muted);
}
.auth-field input, .auth-field select {
padding: 1rem 1.25rem;
border-radius: 10px;
border: 1px solid var(--stroke);
background: var(--surface);
color: var(--ink);
font-family: var(--font-sans-clean);
font-size: 0.95rem;
transition: border-color 0.3s ease, box-shadow 0.3s ease;
outline: none;
}
.auth-field input:focus, .auth-field select:focus {
border-color: var(--color-accent-gold);
box-shadow: 0 0 0 3px var(--accent-soft);
}
.auth-btn-row {
margin-top: 1rem;
}
.auth-btn-row button {
width: 100%;
justify-content: center;
}
.auth-switch-text {
text-align: center;
font-size: 0.9rem;
color: var(--muted);
margin-top: 1.5rem;
}
.auth-switch-text button {
background: none;
border: none;
color: var(--ink);
font-weight: 700;
cursor: pointer;
}
/* ── Profile & Dashboard Styling ── */
.profile-shell {
width: 100%;
max-width: 1100px;
display: grid;
grid-template-columns: 1fr;
gap: 3rem;
}
@media (min-width: 850px) {
.profile-shell {
grid-template-columns: 320px 1fr;
}
}
.profile-sidebar {
background: var(--surface-2);
border: 1px solid var(--stroke);
border-radius: var(--radius);
padding: 2.5rem;
display: flex;
flex-direction: column;
gap: 2rem;
height: fit-content;
box-shadow: var(--shadow);
}
.profile-avatar {
width: 80px;
height: 80px;
border-radius: 50%;
background: var(--accent-soft);
color: var(--color-accent-gold);
display: flex;
align-items: center;
justify-content: center;
font-family: var(--font-serif-display);
font-size: 2.5rem;
border: 1px solid rgba(195,166,119,0.3);
}
.profile-meta h2 {
font-size: 1.75rem;
margin-bottom: 0.25rem;
font-family: var(--font-serif-display);
}
.profile-meta p {
font-size: 0.9rem;
color: var(--muted);
}
.profile-details {
border-top: 1px solid var(--stroke);
padding-top: 1.5rem;
display: flex;
flex-direction: column;
gap: 1.2rem;
}
.profile-stat-box {
display: flex;
flex-direction: column;
gap: 0.3rem;
}
.profile-stat-label {
font-size: 0.72rem;
text-transform: uppercase;
letter-spacing: 0.08em;
font-weight: 700;
color: var(--muted);
}
.profile-stat-val {
font-size: 1rem;
font-weight: 600;
color: var(--ink);
}
.profile-main {
display: flex;
flex-direction: column;
gap: 2rem;
}
.profile-favorites-title {
font-family: var(--font-serif-display);
font-size: 2rem;
border-bottom: 1px solid var(--stroke);
padding-bottom: 0.8rem;
margin-bottom: 1rem;
}
.favorites-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: var(--grid-gap);
}
.favorites-empty {
text-align: center;
padding: 4rem 2rem;
background: var(--surface-2);
border: 1px dashed var(--stroke);
border-radius: var(--radius);
color: var(--muted);
}
/* Alert styling */
.auth-alert {
background: #fdf2f2;
border: 1px solid #fbd5d5;
color: #9b1c1c;
padding: 1rem;
border-radius: 8px;
font-size: 0.9rem;
margin-bottom: 1.5rem;
display: none;
animation: authFadeIn 0.3s ease;
}
[data-theme="dark"] .auth-alert {
background: #2b1515;
border-color: #5a1818;
color: #ff9b9b;
}
/* Loading state spinner */
.spinner {
width: 20px;
height: 20px;
border: 2px solid rgba(255,255,255,0.3);
border-radius: 50%;
border-top-color: #fff;
animation: spin 0.8s linear infinite;
display: none;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.btn-reveal:disabled {
opacity: 0.7;
cursor: not-allowed;
}
.btn-reveal:disabled .spinner {
display: inline-block;
}
.btn-reveal:disabled .btn-reveal-text {
display: none;
}
</style>
<main class="auth-page">
<div class="auth-alert" id="authAlert"></div>
<!-- ── 1. UNAUTHENTICATED STATE (Login/Register Card) ── -->
<div class="auth-card" id="authCard" style="display: <?php echo $user ? 'none' : 'block'; ?>;">
<div class="auth-tabs">
<button class="auth-tab active" onclick="switchTab('login')"><?php echo $t['login']; ?></button>
<button class="auth-tab" onclick="switchTab('signup')"><?php echo $t['signup']; ?></button>
</div>
<!-- Login Form -->
<form class="auth-form active" id="loginForm" onsubmit="handleLogin(event)">
<div class="auth-field">
<label for="loginEmail"><?php echo $t['email']; ?></label>
<input type="email" id="loginEmail" placeholder="you@example.com" required autocomplete="username">
</div>
<div class="auth-field">
<label for="loginPassword"><?php echo $t['password']; ?></label>
<input type="password" id="loginPassword" placeholder="••••••••" required autocomplete="current-password">
</div>
<div class="auth-btn-row">
<button class="btn-reveal" type="submit">
<span class="btn-reveal-text"><?php echo $t['login']; ?></span>
<span class="spinner"></span>
<span class="btn-reveal-arrow">→</span>
</button>
</div>
<p class="auth-switch-text">
<?php echo $t['no_account']; ?> <button type="button" onclick="switchTab('signup')"><?php echo $t['signup']; ?></button>
</p>
</form>
<!-- Sign-up Form -->
<form class="auth-form" id="signupForm" onsubmit="handleSignup(event)">
<div class="auth-field">
<label for="signupEmail"><?php echo $t['email']; ?></label>
<input type="email" id="signupEmail" placeholder="you@example.com" required autocomplete="username">
</div>
<div class="auth-field">
<label for="signupPassword"><?php echo $t['password']; ?></label>
<input type="password" id="signupPassword" placeholder="••••••••" required autocomplete="new-password">
</div>
<div class="auth-field">
<label for="signupConfirm"><?php echo $t['confirm_pass']; ?></label>
<input type="password" id="signupConfirm" placeholder="••••••••" required autocomplete="new-password">
</div>
<div class="auth-field">
<label for="signupGoal"><?php echo $t['goal']; ?></label>
<select id="signupGoal" required>
<option value="" disabled selected><?php echo $t['goal_placeholder']; ?></option>
<option value="weight_loss"><?php echo $t['goal_loose']; ?></option>
<option value="muscle_gain"><?php echo $t['goal_gain']; ?></option>
<option value="healthy"><?php echo $t['goal_healthy']; ?></option>
</select>
</div>
<div class="auth-btn-row">
<button class="btn-reveal" type="submit">
<span class="btn-reveal-text"><?php echo $t['signup']; ?></span>
<span class="spinner"></span>
<span class="btn-reveal-arrow">→</span>
</button>
</div>
<p class="auth-switch-text">
<?php echo $t['have_account']; ?> <button type="button" onclick="switchTab('login')"><?php echo $t['login']; ?></button>
</p>
</form>
</div>
<!-- ── 2. AUTHENTICATED STATE (Dashboard & Favorites) ── -->
<div class="profile-shell" id="profileShell" style="display: <?php echo $user ? 'grid' : 'none'; ?>;">
<aside class="profile-sidebar">
<div style="display: flex; align-items: center; gap: 1.5rem;">
<div class="profile-avatar" id="avatarChar">
<?php echo $user ? strtoupper(substr($user['email'], 0, 1)) : ''; ?>
</div>
<div class="profile-meta">
<p><?php echo $t['welcome']; ?></p>
<h2 id="profileEmailVal"><?php echo $user ? e($user['email']) : ''; ?></h2>
</div>
</div>
<div class="profile-details">
<div class="profile-stat-box">
<span class="profile-stat-label"><?php echo $t['your_goal']; ?></span>
<span class="profile-stat-val" id="profileGoalVal">-</span>
</div>
</div>
<button class="btn-reveal" onclick="handleLogout()" style="margin-top: 1rem; border-color: rgba(0,0,0,0.15);">
<span class="btn-reveal-text"><?php echo $t['logout']; ?></span>
<span class="btn-reveal-arrow">→</span>
</button>
</aside>
<section class="profile-main">
<h3 class="profile-favorites-title"><?php echo $t['saved_recipes']; ?></h3>
<div id="favoritesGrid" class="favorites-grid">
<!-- JS inserts favorited recipe cards here -->
<div class="spinner" style="display: block; margin: 4rem auto; border-top-color: var(--color-accent-gold);"></div>
</div>
<div id="favoritesEmpty" class="favorites-empty" style="display: none;">
<p><?php echo $t['no_favorites']; ?></p>
<a class="btn-reveal" href="/index.php?lang=<?php echo $lang; ?>#recipes-start" style="margin-top: 1.5rem;">
<span class="btn-reveal-text"><?php echo $lang === 'de' ? 'Entdecken' : 'Explore Recipes'; ?></span>
<span class="btn-reveal-arrow">→</span>
</a>
</div>
</section>
</div>
</main>
<script>
// Expose recipe bank to JavaScript
const recipeBank = <?php echo $recipesJson; ?>;
const langText = <?php echo json_encode($t); ?>;
function switchTab(tab) {
const tabs = document.querySelectorAll('.auth-tab');
const forms = document.querySelectorAll('.auth-form');
const alertEl = document.getElementById('authAlert');
alertEl.style.display = 'none';
if (tab === 'login') {
tabs[0].classList.add('active');
tabs[1].classList.remove('active');
forms[0].classList.add('active');
forms[1].classList.remove('active');
} else {
tabs[0].classList.remove('active');
tabs[1].classList.add('active');
forms[0].classList.remove('active');
forms[1].classList.add('active');
}
}
function showAlert(message) {
const alertEl = document.getElementById('authAlert');
alertEl.textContent = message;
alertEl.style.display = 'block';
// Scroll to alert smoothly
window.scrollTo({ top: alertEl.offsetTop - 120, behavior: 'smooth' });
}
function handleLogin(e) {
e.preventDefault();
const email = document.getElementById('loginEmail').value;
const pass = document.getElementById('loginPassword').value;
const btn = e.target.querySelector('button[type="submit"]');
const alertEl = document.getElementById('authAlert');
alertEl.style.display = 'none';
btn.disabled = true;
window.auth.signInWithEmailAndPassword(email, pass)
.then(userCredential => {
// Sync happens automatically via onAuthStateChanged observer in head.php!
// The observer will reload the page when it receives the new state
})
.catch(error => {
btn.disabled = false;
let errMsg = error.message;
if (error.code === 'auth/wrong-password' || error.code === 'auth/user-not-found') {
errMsg = "Invalid email or password.";
}
showAlert(errMsg);
});
}
function handleSignup(e) {
e.preventDefault();
const email = document.getElementById('signupEmail').value;
const pass = document.getElementById('signupPassword').value;
const confirm = document.getElementById('signupConfirm').value;
const goal = document.getElementById('signupGoal').value;
const btn = e.target.querySelector('button[type="submit"]');
const alertEl = document.getElementById('authAlert');
alertEl.style.display = 'none';
if (pass !== confirm) {
showAlert(langText.err_pass_match);
return;
}
btn.disabled = true;
window.auth.createUserWithEmailAndPassword(email, pass)
.then(userCredential => {
const user = userCredential.user;
// Save profile details to Firestore
return window.db.collection('users').doc(user.uid).set({
email: email,
goal: goal,
createdAt: firebase.firestore.FieldValue.serverTimestamp()
});
})
.then(() => {
// Sync is handled by observer in head.php!
})
.catch(error => {
btn.disabled = false;
showAlert(error.message);
});
}
function handleLogout() {
window.auth.signOut()
.then(() => {
// Sync observer takes care of PHP session termination and reloads page
});
}
// ── Profile and Favorites dashboard renderer ──
function initDashboard(user) {
if (!user) return;
const goalVal = document.getElementById('profileGoalVal');
const grid = document.getElementById('favoritesGrid');
const emptyState = document.getElementById('favoritesEmpty');
// Fetch user profile from Firestore
window.db.collection('users').doc(user.uid).get()
.then(doc => {
if (doc.exists) {
const data = doc.data();
let goalString = '-';
if (data.goal === 'weight_loss') goalString = langText.goal_loose;
else if (data.goal === 'muscle_gain') goalString = langText.goal_gain;
else if (data.goal === 'healthy') goalString = langText.goal_healthy;
goalVal.textContent = goalString;
}
})
.catch(err => console.error("Error loading profile: ", err));
// Load Saved Favorites
window.db.collection('user_favorites').where('userId', '==', user.uid).get()
.then(snapshot => {
grid.innerHTML = '';
if (snapshot.empty) {
grid.style.display = 'none';
emptyState.style.display = 'block';
return;
}
emptyState.style.display = 'none';
grid.style.display = 'grid';
snapshot.forEach(doc => {
const fav = doc.data();
const recipe = recipeBank.find(r => r.slug === fav.recipeSlug);
if (recipe) {
const card = document.createElement('article');
card.className = 'card card--bare reveal-target revealed';
card.innerHTML = `
<a href="${recipe.url}" class="card__image">
<img src="${recipe.hero}" alt="${recipe.title}" loading="lazy">
</a>
<div class="card__body">
<h4><a href="${recipe.url}">${recipe.title}</a></h4>
<div class="meta">
<span>⏱ ${recipe.total_time} min</span>
<span>🙂 ${recipe.difficulty}</span>
</div>
</div>
`;
grid.appendChild(card);
}
});
// If none of the favorite slugs matched recipes in current language:
if (grid.children.length === 0) {
grid.style.display = 'none';
emptyState.style.display = 'block';
}
})
.catch(err => {
console.error("Error fetching favorites: ", err);
grid.innerHTML = '<p>Error loading favorites. Please try again.</p>';
});
}
// Observe auth state for dashboard renderer
window.addEventListener('DOMContentLoaded', () => {
window.auth.onAuthStateChanged(user => {
const authCard = document.getElementById('authCard');
const profileShell = document.getElementById('profileShell');
if (user) {
document.getElementById('profileEmailVal').textContent = user.email;
document.getElementById('avatarChar').textContent = user.email.substr(0,1).toUpperCase();
authCard.style.display = 'none';
profileShell.style.display = 'grid';
initDashboard(user);
} else {
authCard.style.display = 'block';
profileShell.style.display = 'none';
}
});
});
</script>
<?php include __DIR__ . '/partials/footer.php'; ?>