/* ── HiTech Technologies — admin.js ─────────────── */ // ── Theme ───────────────────────────────────────── const savedTheme = localStorage.getItem('ht-admin-theme') || 'light'; document.documentElement.setAttribute('data-theme', savedTheme); updateThemeBtn(savedTheme); document.getElementById('adminThemeToggle').addEventListener('click', () => { const cur = document.documentElement.getAttribute('data-theme'); const next = cur === 'dark' ? 'light' : 'dark'; document.documentElement.setAttribute('data-theme', next); localStorage.setItem('ht-admin-theme', next); updateThemeBtn(next); }); function updateThemeBtn(t) { const i = document.querySelector('#adminThemeToggle i'); if (i) i.className = t === 'dark' ? 'fa fa-sun' : 'fa fa-moon'; } // ── Auth ────────────────────────────────────────── let token = localStorage.getItem('ht-admin-token'); let currentUsername = localStorage.getItem('ht-admin-user') || 'Admin'; function getHeaders() { return { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }; } function checkAuth() { if (token) { document.getElementById('login-page').style.display = 'none'; document.getElementById('admin-app').style.display = 'block'; const u = currentUsername; document.getElementById('sidebarName').textContent = u; document.getElementById('sidebarAvatar').textContent = u.charAt(0).toUpperCase(); initAdmin(); } } async function doLogin() { const username = document.getElementById('login-user').value.trim(); const password = document.getElementById('login-pass').value; const btn = document.getElementById('login-btn'); const err = document.getElementById('login-err'); err.style.display = 'none'; if (!username || !password) { showLoginErr('Please enter username and password.'); return; } btn.disabled = true; btn.innerHTML = '
Signing In...'; try { const res = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }); const data = await res.json(); if (res.ok) { token = data.token; currentUsername = data.username; localStorage.setItem('ht-admin-token', token); localStorage.setItem('ht-admin-user', currentUsername); checkAuth(); } else { showLoginErr(data.error || 'Invalid credentials'); } } catch { showLoginErr('Server error. Please try again.'); } finally { btn.disabled = false; btn.innerHTML = ' Sign In'; } } function showLoginErr(msg) { const err = document.getElementById('login-err'); document.getElementById('login-err-msg').textContent = msg; err.style.display = 'block'; } function doLogout() { token = null; localStorage.removeItem('ht-admin-token'); localStorage.removeItem('ht-admin-user'); document.getElementById('admin-app').style.display = 'none'; document.getElementById('login-page').style.display = 'flex'; document.getElementById('login-user').value = ''; document.getElementById('login-pass').value = ''; } // ── Panel switching ─────────────────────────────── const panelTitles = { dashboard:'Dashboard', services:'Manage Services', products:'Manage Products', posts:'Blog Posts', messages:'Contact Messages', settings:'Settings' }; function showPanel(name) { document.querySelectorAll('.panel').forEach(p => p.classList.remove('active')); document.querySelectorAll('.sidebar-link').forEach(l => l.classList.remove('active')); document.getElementById(`panel-${name}`).classList.add('active'); document.querySelector(`[data-panel="${name}"]`).classList.add('active'); document.getElementById('topbarTitle').textContent = panelTitles[name] || name; if (name === 'dashboard') loadDashboard(); if (name === 'services') loadServices(); if (name === 'products') loadProducts(); if (name === 'posts') loadPosts(); if (name === 'messages') loadMessages(); if (name === 'settings') loadSettings(); } // ── API helpers ─────────────────────────────────── async function api(method, path, body) { const opts = { method, headers: getHeaders() }; if (body && !(body instanceof FormData)) { opts.body = JSON.stringify(body); } else if (body instanceof FormData) { opts.headers = { 'Authorization': `Bearer ${token}` }; opts.body = body; } const res = await fetch(path, opts); const data = await res.json().catch(() => ({})); if (res.status === 401) { doLogout(); return; } if (!res.ok) throw new Error(data.error || 'Request failed'); return data; } // ── Dashboard ───────────────────────────────────── async function loadDashboard() { try { const stats = await api('GET', '/api/admin/stats'); document.getElementById('stat-services').textContent = stats.services; document.getElementById('stat-products').textContent = stats.products; document.getElementById('stat-posts').textContent = stats.posts; document.getElementById('stat-contacts').textContent = stats.contacts; document.getElementById('stat-unread').textContent = stats.unread; if (stats.unread > 0) { document.getElementById('unreadBadge').textContent = stats.unread; document.getElementById('unreadBadge').style.display = 'inline'; } else document.getElementById('unreadBadge').style.display = 'none'; loadDashMsgs(); } catch (e) { showToast('Failed to load stats', 'error'); } } async function loadDashMsgs() { try { const msgs = await api('GET', '/api/contacts'); const el = document.getElementById('dashMsgs'); if (!msgs.length) { el.innerHTML = '

No messages yet.

'; return; } el.innerHTML = msgs.slice(0, 5).map(m => `
${m.name} ${!m.is_read ? 'New' : ''}
${m.message}
${new Date(m.created_at).toLocaleDateString()}
`).join(''); } catch {} } // ── Services CRUD ───────────────────────────────── let allServices = [], editingSvcId = null, svcBannerFile = null; async function loadServices() { const el = document.getElementById('svcList'); try { allServices = await api('GET', '/api/services?all=1'); document.getElementById('svcCount').textContent = allServices.length; renderServiceList(allServices); } catch { el.innerHTML = '

Failed to load.

'; } } function renderServiceList(list) { const el = document.getElementById('svcList'); if (!list.length) { el.innerHTML = '

No services yet. Add your first service.

'; return; } el.innerHTML = list.map(s => `
${s.banner_url ? `
${s.name}
` : `
`}
${s.name} ${s.status}
${s.description || 'No description'}
`).join(''); } function editService(id) { const s = allServices.find(x => x.id === id); if (!s) return; editingSvcId = id; document.getElementById('svc-edit-id').value = id; document.getElementById('svc-name').value = s.name; document.getElementById('svc-desc').value = s.desc || s.description || ''; document.getElementById('svc-icon').value = s.icon || ''; document.getElementById('svc-features').value = s.features || ''; document.getElementById('svc-status').value = s.status || 'active'; document.getElementById('svc-order').value = s.sort_order || 0; if (s.banner_url) { setBannerPreview('svc', s.banner_url); } else { clearBannerPreview('svc'); } document.getElementById('svcFormTitle').textContent = 'Edit Service'; document.getElementById('svcSaveLbl').textContent = 'Update Service'; document.getElementById('svcCancelBtn').style.display = 'inline-flex'; document.getElementById('svcFormCard').scrollIntoView({ behavior: 'smooth' }); } async function saveService() { const name = document.getElementById('svc-name').value.trim(); if (!name) { showToast('Service name is required.', 'error'); return; } const fd = new FormData(); fd.append('name', name); fd.append('description', document.getElementById('svc-desc').value); fd.append('icon', document.getElementById('svc-icon').value); fd.append('features', document.getElementById('svc-features').value); fd.append('status', document.getElementById('svc-status').value); fd.append('sort_order', document.getElementById('svc-order').value); if (svcBannerFile) fd.append('banner', svcBannerFile); try { if (editingSvcId) { await api('PUT', `/api/services/${editingSvcId}`, fd); showToast('Service updated!', 'success'); } else { await api('POST', '/api/services', fd); showToast('Service added!', 'success'); } resetServiceForm(); loadServices(); } catch (e) { showToast(e.message, 'error'); } } function resetServiceForm() { editingSvcId = null; svcBannerFile = null; ['svc-name','svc-desc','svc-icon','svc-features'].forEach(id => document.getElementById(id).value = ''); document.getElementById('svc-status').value = 'active'; document.getElementById('svc-order').value = 0; clearBannerPreview('svc'); document.getElementById('svcFormTitle').textContent = 'Add New Service'; document.getElementById('svcSaveLbl').textContent = 'Add Service'; document.getElementById('svcCancelBtn').style.display = 'none'; } // ── Products CRUD ───────────────────────────────── let allProducts = [], editingProdId = null, prodBannerFile = null; async function loadProducts() { const el = document.getElementById('prodList'); try { allProducts = await api('GET', '/api/products?all=1'); document.getElementById('prodCount').textContent = allProducts.length; renderProductList(allProducts); } catch { el.innerHTML = '

Failed to load.

'; } } function renderProductList(list) { const el = document.getElementById('prodList'); if (!list.length) { el.innerHTML = '

No products yet.

'; return; } el.innerHTML = list.map(p => `
${p.banner_url ? `
${p.name}
` : `
`}
${p.name} ${p.category || p.status}
${p.description || 'No description'}
`).join(''); } function editProduct(id) { const p = allProducts.find(x => x.id === id); if (!p) return; editingProdId = id; document.getElementById('prod-edit-id').value = id; document.getElementById('prod-name').value = p.name; document.getElementById('prod-category').value = p.category || ''; document.getElementById('prod-desc').value = p.description || ''; document.getElementById('prod-features').value = (p.features || '').replace(/,/g, '\n'); document.getElementById('prod-color').value = p.banner_color || '#0D2B7A'; document.getElementById('prod-status').value = p.status || 'active'; if (p.banner_url) setBannerPreview('prod', p.banner_url); else clearBannerPreview('prod'); document.getElementById('prodFormTitle').textContent = 'Edit Product'; document.getElementById('prodSaveLbl').textContent = 'Update Product'; document.getElementById('prodCancelBtn').style.display = 'inline-flex'; } async function saveProduct() { const name = document.getElementById('prod-name').value.trim(); if (!name) { showToast('Product name is required.', 'error'); return; } const rawFeatures = document.getElementById('prod-features').value; const features = rawFeatures.includes('\n') ? rawFeatures.split('\n').map(f=>f.trim()).filter(Boolean).join(',') : rawFeatures; const fd = new FormData(); fd.append('name', name); fd.append('category', document.getElementById('prod-category').value); fd.append('description', document.getElementById('prod-desc').value); fd.append('features', features); fd.append('banner_color', document.getElementById('prod-color').value); fd.append('status', document.getElementById('prod-status').value); if (prodBannerFile) fd.append('banner', prodBannerFile); try { if (editingProdId) { await api('PUT', `/api/products/${editingProdId}`, fd); showToast('Product updated!', 'success'); } else { await api('POST', '/api/products', fd); showToast('Product added!', 'success'); } resetProductForm(); loadProducts(); } catch (e) { showToast(e.message, 'error'); } } function resetProductForm() { editingProdId = null; prodBannerFile = null; ['prod-name','prod-category','prod-desc','prod-features'].forEach(id => document.getElementById(id).value = ''); document.getElementById('prod-color').value = '#0D2B7A'; document.getElementById('prod-status').value = 'active'; clearBannerPreview('prod'); document.getElementById('prodFormTitle').textContent = 'Add New Product'; document.getElementById('prodSaveLbl').textContent = 'Add Product'; document.getElementById('prodCancelBtn').style.display = 'none'; } // ── Posts CRUD ──────────────────────────────────── let allPosts = [], editingPostId = null, postBannerFile = null; async function loadPosts() { const el = document.getElementById('postList'); try { allPosts = await api('GET', '/api/posts?all=1'); document.getElementById('postCount').textContent = allPosts.length; renderPostList(allPosts); } catch { el.innerHTML = '

Failed to load.

'; } } function renderPostList(list) { const el = document.getElementById('postList'); if (!list.length) { el.innerHTML = '

No posts yet.

'; return; } el.innerHTML = list.map(p => `
${p.banner_url ? `
${p.title}
` : `
`}
${p.title} ${p.status}
${p.excerpt || (p.content||'').substring(0,80) || 'No content'}
`).join(''); } function editPost(id) { const p = allPosts.find(x => x.id === id); if (!p) return; editingPostId = id; document.getElementById('post-edit-id').value = id; document.getElementById('post-title').value = p.title; document.getElementById('post-excerpt').value = p.excerpt || ''; document.getElementById('post-content').value = p.content || ''; document.getElementById('post-status').value = p.status || 'published'; if (p.banner_url) setBannerPreview('post', p.banner_url); else clearBannerPreview('post'); document.getElementById('postFormTitle').textContent = 'Edit Post'; document.getElementById('postSaveLbl').textContent = 'Update Post'; document.getElementById('postCancelBtn').style.display = 'inline-flex'; } async function savePost() { const title = document.getElementById('post-title').value.trim(); if (!title) { showToast('Post title is required.', 'error'); return; } const fd = new FormData(); fd.append('title', title); fd.append('excerpt', document.getElementById('post-excerpt').value); fd.append('content', document.getElementById('post-content').value); fd.append('status', document.getElementById('post-status').value); if (postBannerFile) fd.append('banner', postBannerFile); try { if (editingPostId) { await api('PUT', `/api/posts/${editingPostId}`, fd); showToast('Post updated!', 'success'); } else { await api('POST', '/api/posts', fd); showToast('Post published!', 'success'); } resetPostForm(); loadPosts(); } catch (e) { showToast(e.message, 'error'); } } function resetPostForm() { editingPostId = null; postBannerFile = null; ['post-title','post-excerpt','post-content'].forEach(id => document.getElementById(id).value = ''); document.getElementById('post-status').value = 'published'; clearBannerPreview('post'); document.getElementById('postFormTitle').textContent = 'Add New Post'; document.getElementById('postSaveLbl').textContent = 'Publish Post'; document.getElementById('postCancelBtn').style.display = 'none'; } // ── Messages ────────────────────────────────────── let allMsgs = [], msgFilter = 'all'; async function loadMessages() { const el = document.getElementById('msgsList'); try { allMsgs = await api('GET', '/api/contacts'); renderMessages(allMsgs); } catch { el.innerHTML = '

Failed to load messages.

'; } } function filterMsgs(f) { msgFilter = f; renderMessages(allMsgs); } function renderMessages(list) { const el = document.getElementById('msgsList'); const filtered = msgFilter === 'unread' ? list.filter(m => !m.is_read) : list; if (!filtered.length) { el.innerHTML = '

No messages found.

'; return; } el.innerHTML = filtered.map(m => `
${m.name || 'Unknown'} ${!m.is_read ? 'New' : 'Read'}
${m.email || 'No email'}  ·  ${m.phone || 'No phone'}
${new Date(m.created_at).toLocaleDateString('en-PK', {year:'numeric',month:'short',day:'numeric'})}
${m.message || 'No message'}
${m.service_interest ? `
Service Interest
${m.service_interest}
` : ''} ${m.budget ? `
Budget
${m.budget}
` : ''}
${!m.is_read ? `` : ''} ${m.email ? ` Reply` : ''} ${m.phone ? ` WhatsApp` : ''}
`).join(''); } async function toggleMsg(id) { const body = document.getElementById(`msgBody-${id}`); const isOpen = body.classList.contains('open'); document.querySelectorAll('.msg-body').forEach(b => b.classList.remove('open')); if (!isOpen) { body.classList.add('open'); const msg = allMsgs.find(m => m.id === id); if (msg && !msg.is_read) { await markRead(id, true); } } } async function markRead(id, silent = false) { try { await api('PUT', `/api/contacts/${id}/read`); const msg = allMsgs.find(m => m.id === id); if (msg) msg.is_read = 1; renderMessages(allMsgs); if (!silent) showToast('Marked as read', 'success'); } catch (e) { if (!silent) showToast('Failed to update', 'error'); } } // ── Settings ────────────────────────────────────── const settingGroups = { company: ['company_name', 'tagline', 'phone', 'email', 'address', 'working_hours'], content: ['hero_title', 'hero_subtitle', 'about_text', 'footer_text'], social: ['facebook', 'linkedin', 'twitter', 'whatsapp'] }; async function loadSettings() { try { const s = await api('GET', '/api/settings'); Object.values(settingGroups).flat().forEach(key => { const el = document.getElementById(`s-${key}`); if (el) el.value = s[key] || ''; }); } catch (e) { showToast('Failed to load settings', 'error'); } } async function saveSettings(group) { const keys = settingGroups[group]; const data = {}; keys.forEach(key => { const el = document.getElementById(`s-${key}`); if (el) data[key] = el.value; }); try { await api('PUT', '/api/settings', data); showToast('Settings saved successfully!', 'success'); } catch (e) { showToast(e.message, 'error'); } } async function changePassword() { const cur = document.getElementById('cur-pass').value; const nw = document.getElementById('new-pass').value; const conf = document.getElementById('conf-pass').value; if (!cur || !nw || !conf) { showToast('All fields required', 'error'); return; } if (nw !== conf) { showToast('New passwords do not match', 'error'); return; } if (nw.length < 4) { showToast('Password must be at least 4 characters', 'error'); return; } try { await api('POST', '/api/auth/change-password', { currentPassword: cur, newPassword: nw }); showToast('Password changed successfully!', 'success'); ['cur-pass','new-pass','conf-pass'].forEach(id => document.getElementById(id).value = ''); } catch (e) { showToast(e.message, 'error'); } } // ── Delete Modal ────────────────────────────────── let deleteTarget = { type: null, id: null }; function openDelete(type, id) { deleteTarget = { type, id }; document.getElementById('deleteModal').classList.add('open'); } function closeModal() { document.getElementById('deleteModal').classList.remove('open'); } async function confirmDelete() { const { type, id } = deleteTarget; const urlMap = { service: `/api/services/${id}`, product: `/api/products/${id}`, post: `/api/posts/${id}`, message: `/api/contacts/${id}` }; try { await api('DELETE', urlMap[type]); showToast(`${type.charAt(0).toUpperCase()+type.slice(1)} deleted.`, 'success'); closeModal(); if (type === 'service') loadServices(); if (type === 'product') loadProducts(); if (type === 'post') loadPosts(); if (type === 'message') loadMessages(); } catch (e) { showToast(e.message, 'error'); } } // ── Filter lists ────────────────────────────────── function filterList(type, q) { q = q.toLowerCase(); if (type === 'svc') renderServiceList(allServices.filter(s => s.name.toLowerCase().includes(q) || (s.description||'').toLowerCase().includes(q))); if (type === 'prod') renderProductList(allProducts.filter(p => p.name.toLowerCase().includes(q) || (p.description||'').toLowerCase().includes(q))); if (type === 'post') renderPostList(allPosts.filter(p => p.title.toLowerCase().includes(q))); } // ── Banner preview ──────────────────────────────── const bannerFiles = { svc: null, prod: null, post: null }; function previewFile(type) { const fileInput = document.getElementById(`${type}-banner-file`); const file = fileInput.files[0]; if (!file) return; if (type === 'svc') svcBannerFile = file; if (type === 'prod') prodBannerFile = file; if (type === 'post') postBannerFile = file; const reader = new FileReader(); reader.onload = e => setBannerPreview(type, e.target.result); reader.readAsDataURL(file); } function setBannerPreview(type, src) { const img = document.getElementById(`${type}BannerImg`); const drop = document.getElementById(`${type}BannerDrop`); img.src = src; img.style.display = 'block'; drop.querySelector('i').style.display = 'none'; drop.querySelector('span').style.display = 'none'; } function clearBannerPreview(type) { const img = document.getElementById(`${type}BannerImg`); const drop = document.getElementById(`${type}BannerDrop`); img.src = ''; img.style.display = 'none'; drop.querySelector('i').style.display = ''; drop.querySelector('span').style.display = ''; } // ── Toast ───────────────────────────────────────── function showToast(msg, type = '') { const t = document.getElementById('a-toast'); t.textContent = msg; t.className = `show ${type}`; clearTimeout(t._t); t._t = setTimeout(() => t.className = '', 3500); } // ── Init ────────────────────────────────────────── function initAdmin() { showPanel('dashboard'); } checkAuth();