Refactor database handling to require PostgreSQL connection, removing fallback to JSON. Implement error handling for database unavailability in key files. Update .env.example to reflect mandatory DATABASE_URL for local development. Remove Firebase configuration and related code from the project.

This commit is contained in:
2026-05-23 10:23:28 +02:00
parent 547778bba5
commit 6577db475a
20 changed files with 823 additions and 789 deletions
+89 -259
View File
@@ -1,6 +1,12 @@
<?php
require __DIR__ . '/helpers.php';
try {
$allRecipes = load_recipes();
} catch (DatabaseUnavailableException $e) {
handle_database_unavailable($e);
}
$lang = (isset($_GET['lang']) && strtolower($_GET['lang']) === 'de') ? 'de' : 'en';
$copy = [
@@ -23,9 +29,9 @@ $copy = [
'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.',
'save_goal' => 'Save goal',
'goal_saved' => 'Dietary goal saved.',
'local_note' => 'Favorites and goals are stored in this browser only.',
],
'de' => [
'page_title' => 'Mein Profil & Favoriten | FlixCooks',
@@ -46,9 +52,9 @@ $copy = [
'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.',
'save_goal' => 'Ziel speichern',
'goal_saved' => 'Ernährungsziel gespeichert.',
'local_note' => 'Favoriten und Ziele werden nur in diesem Browser gespeichert.',
]
];
@@ -56,10 +62,6 @@ $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
@@ -376,95 +378,37 @@ include __DIR__ . '/partials/header.php';
<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'; ?>;">
<div class="profile-shell" id="profileShell" style="display: grid;">
<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 class="profile-meta">
<p><?php echo $t['welcome']; ?></p>
<p style="font-size: 0.9rem; color: var(--muted); margin-top: 0.5rem;"><?php echo e($t['local_note']); ?></p>
</div>
<div class="profile-details">
<form class="auth-form active" id="goalForm" onsubmit="handleSaveGoal(event)" style="margin-top: 1.5rem;">
<div class="auth-field">
<label for="profileGoal"><?php echo $t['goal']; ?></label>
<select id="profileGoal" required>
<option value="" disabled><?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['save_goal']; ?></span>
<span class="btn-reveal-arrow">→</span>
</button>
</div>
</form>
<div class="profile-details" style="margin-top: 1.5rem;">
<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">
@@ -487,195 +431,81 @@ include __DIR__ . '/partials/header.php';
</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 goalLabel(goal) {
if (goal === 'weight_loss') return langText.goal_loose;
if (goal === 'muscle_gain') return langText.goal_gain;
if (goal === 'healthy') return langText.goal_healthy;
return '-';
}
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) {
function handleSaveGoal(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);
});
if (!window.fcLocal) return;
const goal = document.getElementById('profileGoal').value;
window.fcLocal.setGoal(goal);
document.getElementById('profileGoalVal').textContent = goalLabel(goal);
showAlert(langText.goal_saved);
}
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');
function renderFavorites() {
const grid = document.getElementById('favoritesGrid');
const emptyState = document.getElementById('favoritesEmpty');
if (!window.fcLocal) return;
alertEl.style.display = 'none';
const slugs = window.fcLocal.getFavorites();
grid.innerHTML = '';
if (pass !== confirm) {
showAlert(langText.err_pass_match);
if (slugs.length === 0) {
grid.style.display = 'none';
emptyState.style.display = 'block';
return;
}
btn.disabled = true;
emptyState.style.display = 'none';
grid.style.display = 'grid';
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';
}
slugs.forEach(function(slug) {
const recipe = recipeBank.find(function(r) { return r.slug === slug; });
if (!recipe) return;
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 (grid.children.length === 0) {
grid.style.display = 'none';
emptyState.style.display = 'block';
}
}
window.addEventListener('DOMContentLoaded', function() {
if (!window.fcLocal) return;
const goal = window.fcLocal.getGoal();
const select = document.getElementById('profileGoal');
if (goal && select) select.value = goal;
document.getElementById('profileGoalVal').textContent = goalLabel(goal);
renderFavorites();
});
</script>