/* ═══════════════════════════════════════════ AUTH ═══════════════════════════════════════════ */ function switchAuthTab(tab) { ['login','signup','forgot'].forEach(t => { document.getElementById('auth-' + t)?.classList.remove('active'); }); document.getElementById('auth-' + tab)?.classList.add('active'); document.getElementById('tab-login')?.classList.toggle('active', tab === 'login'); document.getElementById('tab-signup')?.classList.toggle('active', tab === 'signup'); } function showForgot() { switchAuthTab('forgot'); } function showLogin() { switchAuthTab('login'); } function togglePass(id, btn) { const inp = document.getElementById(id); if (inp.type === 'password') { inp.type = 'text'; btn.textContent = '🙈'; } else { inp.type = 'password'; btn.textContent = '👁'; } } function doLogin() { const email = document.getElementById("login-email").value.trim(); const pass = document.getElementById("login-pass").value; if (!email || !pass) { toast("⚠ Please fill all fields"); return; } fetch("api/login.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email: email, password: pass }) }) .then(res => { if (!res.ok) { return res.text().then(text => { throw new Error(text) }); } return res.json(); }) .then(data => { if (data.status === "success") { currentUser = data.user; currentUser.isAdmin = data.user.role === 'admin'; afterLogin(); } else { toast("❌ " + (data.message || "Invalid login")); } }) .catch(err => { console.error("Login Error:", err); toast("❌ Connection error. See console."); }); } function doSignup() { const name = document.getElementById('su-name').value.trim(); const email = document.getElementById('su-email').value.trim(); const phone = document.getElementById('su-phone').value.trim(); const pass = document.getElementById('su-pass').value; if (!name || !email || !phone || !pass) { toast('⚠ Please fill all fields'); return; } fetch("api/signup.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name, email, phone, password: pass }) }) .then(res => { if (!res.ok) { return res.text().then(text => { throw new Error(text) }); } return res.json(); }) .then(data => { if (data.status === "success") { toast("✅ Account created! Please log in."); switchAuthTab('login'); } else { toast("❌ " + (data.message || "Signup failed")); } }) .catch(err => { console.error("Signup Error:", err); toast("❌ Connection error. See console."); }); } function doSocialLogin(type) { currentUser = { name: 'Student', email: 'student@kiit.ac.in', phone: '8809989XXX' }; toast('✅ Signed in with ' + type); afterLogin(); } function doAdminLogin() { const email = "admin@kiitkafe.in"; const pass = "admin123"; fetch("api/login.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email: email, password: pass }) }) .then(res => res.json()) .then(data => { if (data.status === "success" && data.user.role === 'admin') { currentUser = data.user; currentUser.isAdmin = true; afterLogin(); } else { toast("❌ Admin credentials invalid"); } }) .catch(err => toast("❌ Connection error")); } function doForgot() { const email = document.getElementById('forgot-email').value.trim(); if (!email) { toast('⚠ Enter your email'); return; } const newPass = prompt('Enter new password:'); if (!newPass) return; fetch("api/forgot_password.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email: email, new_password: newPass }) }) .then(res => res.json()) .then(data => { if (data.status === "success") { toast('✅ Password updated! Please login.'); showLogin(); } else { toast('❌ ' + (data.message || "Update failed")); } }) .catch(err => toast('❌ Connection error')); } function afterLogin() { document.getElementById('welcome-name').textContent = currentUser.name; if (currentUser.isAdmin) { toast('🔑 Admin Access: Welcome, ' + currentUser.name + '!'); nav('admin'); } else { toast('🎉 Welcome, ' + currentUser.name + '!'); nav('menu'); } } function doLogout() { fetch("api/logout.php") .then(() => { currentUser = null; cart = []; discount = 0; updateCartIndicators(); closeModal('account-modal'); toast('👋 Logged out successfully'); nav('landing'); }) .catch(err => { console.error("Logout error:", err); toast("❌ Logout failed. Try again."); }); } function showAccountMenu() { if (!currentUser) { nav('auth'); return; } document.getElementById('account-modal-name').textContent = currentUser.name; document.getElementById('account-modal-email').textContent = currentUser.email; document.getElementById('account-modal-phone').textContent = currentUser.phone || 'Not set'; loadOrderHistory(); document.getElementById('account-modal').classList.add('show'); } function loadOrderHistory() { const container = document.getElementById('order-history-list'); container.innerHTML = '
Loading orders...
'; fetch("api/get_user_orders.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ user_id: currentUser.id }) }) .then(res => { console.log("Response status:", res.status); if (!res.ok) { throw new Error("HTTP error: " + res.status); } return res.json(); }) .then(data => { console.log("Order data:", data); if (data.status === "success" && data.orders.length > 0) { container.innerHTML = data.orders.map(order => { const statusColors = { 'Pending': '#f59e0b', 'Preparing': '#3b82f6', 'Completed': '#22c55e', 'Failed': '#ef4444', 'Invalid': '#6b7280' }; const statusColor = statusColors[order.status] || '#888'; const date = new Date(order.created_at); const dateStr = date.toLocaleDateString('en-IN', { day: 'numeric', month: 'short', year: 'numeric' }); const timeStr = date.toLocaleTimeString('en-IN', { hour: '2-digit', minute: '2-digit' }); return `
#${order.order_code} ${order.status}
📅 ${dateStr} · ${timeStr}
${order.items || 'No items'}
${order.total_items} item(s) ₹${order.total}
`; }).join(''); } else if (data.status === "success") { container.innerHTML = '
📭 No orders yet
'; } else { console.error("API error:", data.message); container.innerHTML = '
❌ ' + (data.message || 'Failed to load orders') + '
'; } }) .catch(err => { console.error("Order history error:", err); container.innerHTML = '
❌ Error: ' + err.message + '
'; }); } function updateProfile() { closeModal('account-modal'); // Create edit profile modal dynamically const modal = document.createElement('div'); modal.className = 'modal-overlay show'; modal.id = 'edit-profile-modal'; modal.innerHTML = `

✏️ Edit Profile

Must be at least 6 characters
`; document.body.appendChild(modal); modal.addEventListener('click', e => { if (e.target === modal) { closeModal('edit-profile-modal'); setTimeout(()=>showAccountMenu(), 100); } }); } function saveProfileChanges() { const name = document.getElementById('edit-name').value.trim(); const phone = document.getElementById('edit-phone').value.trim(); const currentPass = document.getElementById('current-pass').value; const newPass = document.getElementById('new-pass').value; if (!name) { toast('⚠️ Name is required'); return; } if (!currentPass) { toast('⚠️ Current password is required'); return; } if (newPass && newPass.length < 6) { toast('⚠️ New password must be at least 6 characters'); return; } fetch("api/update_profile.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ user_id: currentUser.id, name: name, phone: phone, password: newPass || null, current_password: currentPass }) }) .then(res => res.json()) .then(data => { if (data.status === "success") { currentUser.name = name; currentUser.phone = phone; document.getElementById('welcome-name').textContent = name; document.getElementById('account-modal-name').textContent = name; toast('✅ Profile updated successfully'); closeModal('edit-profile-modal'); setTimeout(()=>showAccountMenu(), 100); } else { toast('❌ ' + data.message); } }) .catch(err => { console.error(err); toast('❌ Connection error'); }); }