AMBI COMPUTERS โ€” SaaS Suite
Multi-Tenant Workforce, GPS Attendance & White-Label ERP โ€ข www.ambicomputers.com โ€ข ๐Ÿ“ž 9543364416
09:41 apk.ambicomputers.com โ— Online
Tenant Workspace Setup
Select Your Company
AMBI COMPUTERS โ€ข 9543364416
๐Ÿข

Company Admin Portal

Sign in with your Company Password or Registered Mobile SMS OTP

app.ambicomputers.com โ€ข Support: ๐Ÿ“ž 9543364416
๐Ÿ‘‘

Master Super-Admin Login

AMBI COMPUTERS โ€ข SaaS Tenant & White-Label Control

`); doc.close(); setTimeout(() => { iframe.contentWindow.focus(); iframe.contentWindow.print(); }, 200); } catch (e) { window.print(); } } function downloadCurrentModalHtml() { const fullHtml = `${escapeHtmlSafe(state.lastModalTitle)}
${state.lastModalHtml}`; const blob = new Blob([fullHtml], { type: 'text/html;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `${state.lastModalTitle.replace(/[^A-Za-z0-9]/g, '_')}.html`; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => URL.revokeObjectURL(url), 4000); showToast('โฌ‡๏ธ Downloaded PDF/HTML Document!', '#10b981'); } function printTargetSection(modeClass) { if (modeClass === 'print-report-only') { const repPanel = document.getElementById('web-panel-reports'); const clone = repPanel.cloneNode(true); clone.querySelectorAll('.no-print').forEach(el => el.remove()); const repHeading = document.getElementById('rep-comp-title')?.textContent || 'Monthly Report'; openInAppPrintPreview(repHeading, getCompanyPrintHeaderHtml(repHeading) + clone.innerHTML); return; } if (modeClass === 'print-payslip-only') { const compTitle = document.getElementById('pay-comp-heading')?.textContent || `${state.companyName} โ€” SALARY SLIP`; const slipHtml = document.getElementById('payslip-printable-box')?.outerHTML || ''; openInAppPrintPreview(compTitle, `${getCompanyPrintHeaderHtml('MONTHLY SALARY PAYSLIP')}${slipHtml}
Employee Signature
Authorized Signatory (${escapeHtmlSafe(state.companyName)})
`); return; } if (modeClass === 'print-invoice-only') { const invCard = document.getElementById('master-gst-invoice-card'); if (!invCard || invCard.classList.contains('hidden')) { showToast('Generate a GST Invoice first!', '#e11d48'); return; } const clone = invCard.cloneNode(true); clone.querySelectorAll('.no-print').forEach(el => el.remove()); openInAppPrintPreview('AMBI COMPUTERS โ€” GST Tax Invoice', clone.innerHTML); return; } window.print(); } function downloadPrintableDocument(docType) { printTargetSection(docType === 'PAYSLIP' ? 'print-payslip-only' : (docType === 'INVOICE' ? 'print-invoice-only' : 'print-report-only')); downloadCurrentModalHtml(); } function buildSectionReportHtml(kind, singleItemId = null) { if (kind === 'PETROL') { const filterEmp = singleItemId ? 'SINGLE' : (document.getElementById('web-exp-print-staff-filter')?.value || 'ALL'); let list = state.expenses.filter(ex => (ex.companyRegId || 'AJSL-2026') === state.companyRegId); if (singleItemId) list = list.filter(ex => ex.id === singleItemId); else if (filterEmp !== 'ALL') list = list.filter(ex => ex.empId === filterEmp); const total = list.reduce((s, e) => s + Number(e.amount || 0), 0); const rows = list.map(e => `${e.date}${escapeHtmlSafe(e.empName)} (${e.empId})${escapeHtmlSafe(e.category)}${escapeHtmlSafe(e.note)}โ‚น${e.amount}`).join(''); return { title: `${state.companyName} โ€” Petrol & Field Expenses Statement`, html: `${getCompanyPrintHeaderHtml('PETROL & FIELD EXPENSE REPORT')}
Total Entries: ${list.length} โ€ข Total Amount: โ‚น${total}
${rows || ''}
DateStaffCategoryRoute / DetailsAmount
No records
` }; } if (kind === 'FIELD_REPORT') { const filterEmp = singleItemId ? 'SINGLE' : (document.getElementById('web-trips-staff-filter')?.value || 'ALL'); let list = state.trips.filter(t => (t.companyRegId || 'AJSL-2026') === state.companyRegId); if (singleItemId) list = list.filter(t => t.id === singleItemId); else if (filterEmp !== 'ALL') list = list.filter(t => t.empId === filterEmp); const totalKm = list.reduce((s, t) => s + Number(t.km || 0), 0); const rows = list.map(t => `${t.date}${escapeHtmlSafe(t.empName)} (${t.vehicle})${escapeHtmlSafe(t.startPlace)}${escapeHtmlSafe(t.endPlace)}${t.km} kmโ‚น${t.amount} (${escapeHtmlSafe(t.customer)})`).join(''); return { title: `${state.companyName} โ€” Field Visit & Trip Report`, html: `${getCompanyPrintHeaderHtml('FIELD VISIT & KM REPORT')}
Total Trips: ${list.length} โ€ข Total Distance: ${totalKm.toFixed(1)} km
${rows || ''}
DateStaff & VehicleStart PlaceEnd PlaceKMAmount & Client
No records
` }; } const filterEmp = singleItemId ? 'SINGLE' : (document.getElementById('web-adv-print-staff-filter')?.value || 'ALL'); let list = state.salaryAdvances.filter(a => (a.companyRegId || 'AJSL-2026') === state.companyRegId); if (singleItemId) list = list.filter(a => a.id === singleItemId); else if (filterEmp !== 'ALL') list = list.filter(a => a.empId === filterEmp); const totalAdv = list.reduce((s, a) => s + Number(a.amount || 0), 0); const rows = list.map(a => `${a.date}${escapeHtmlSafe(a.empName)} (${a.empId})โ‚น${a.amount}${escapeHtmlSafe(a.reason)}${a.status}`).join(''); return { title: `${state.companyName} โ€” Salary Advance Statement`, html: `${getCompanyPrintHeaderHtml('SALARY ADVANCE REPORT')}
Total Records: ${list.length} โ€ข Total Advance: โ‚น${totalAdv}
${rows || ''}
DateStaffAmountReasonStatus
No records
` }; } function printSectionReport(kind, singleItemId = null) { const doc = buildSectionReportHtml(kind, singleItemId); openInAppPrintPreview(doc.title, doc.html); } function downloadSectionReport(kind, singleItemId = null) { printSectionReport(kind, singleItemId); downloadCurrentModalHtml(); } /* ================= TIER 1: ANDROID APK LOGIC ================= */ function syncApkVehicleRateFromAdmin() { const vehSel = document.getElementById('apk-trip-vehicle'); const rateInp = document.getElementById('apk-trip-rate'); if (!vehSel || !rateInp) return; const comp = state.registeredCompanies.find(c => c.regId === state.companyRegId); const bRate = (comp && comp.bikeKmRate) || state.bikeKmRate || 4; const cRate = (comp && comp.carKmRate) || state.carKmRate || 10; rateInp.value = vehSel.value === 'Car' ? cRate : bRate; } function updateCompanyKmRates() { const bVal = Number(document.getElementById('admin-bike-km-rate')?.value); const cVal = Number(document.getElementById('admin-car-km-rate')?.value); const comp = state.registeredCompanies.find(c => c.regId === state.companyRegId); if (bVal > 0) { state.bikeKmRate = bVal; if (comp) comp.bikeKmRate = bVal; } if (cVal > 0) { state.carKmRate = cVal; if (comp) comp.carKmRate = cVal; } savePersistentState(); syncApkVehicleRateFromAdmin(); renderApk(); showToast(`๐Ÿ๏ธ KM Rate Synced to APK: Bike โ‚น${state.bikeKmRate}/km โ€ข Car โ‚น${state.carKmRate}/km`, '#10b981'); } function handleApkCompanySearchInput(val) { const q = (val || '').trim().toLowerCase(); const box = document.getElementById('apk-company-live-results'); const nf = document.getElementById('apk-company-not-found'); if (!box) return; nf.classList.add('hidden'); const activeList = state.registeredCompanies.filter(c => c.active !== false); const matches = q ? activeList.filter(c => c.name.toLowerCase().includes(q) || c.regId.toLowerCase().includes(q)) : activeList; if (!matches.length) { box.innerHTML = ''; nf.classList.remove('hidden'); return; } box.innerHTML = matches.map(c => `
${escapeHtmlSafe(c.name)}
${escapeHtmlSafe(c.regId)} โ€ข ${escapeHtmlSafe(c.address || 'India')}
`).join(''); } function syncTypedCompanyNameNow() { const q = (document.getElementById('apk-company-name-input')?.value || '').trim().toLowerCase(); const activeList = state.registeredCompanies.filter(c => c.active !== false); const target = activeList.find(c => c.name.toLowerCase().includes(q) || c.regId.toLowerCase().includes(q)) || activeList[0]; if (target) selectApkCompanyAndGoStaffLogin(target.regId); } function selectApkCompanyAndGoStaffLogin(regId) { const found = state.registeredCompanies.find(c => c.regId === regId); if (!found || found.active === false) return; activateRegisteredCompany(found.regId, false); state.apkLinked = true; state.mobileLoggedIn = false; renderApk(); showToast(`Synced: ${found.name}`, '#10b981'); } function handleApkStaffLetterFilter(val) { const q = (val || '').trim().toLowerCase(); const box = document.getElementById('apk-staff-live-results'); if (!box) return; const compStaff = state.employees.filter(e => (e.companyRegId || 'AJSL-2026') === state.companyRegId); const matches = q ? compStaff.filter(e => e.name.toLowerCase().includes(q) || e.empId.toLowerCase().includes(q)) : compStaff; box.innerHTML = matches.map(e => `
${escapeHtmlSafe(e.name)}
${escapeHtmlSafe(e.empId)} โ€ข ${escapeHtmlSafe(e.role)}
`).join(''); } function confirmApkStaffSelectionOk(empId) { const emp = state.employees.find(e => e.empId === empId); if (!emp) return; state.currentEmpId = emp.empId; document.getElementById('apk-staff-search-input').value = `${emp.empId} โ€” ${emp.name}`; document.getElementById('apk-staff-live-results').innerHTML = ''; document.getElementById('apk-login-pin')?.focus(); } function handleMobileLogin() { const rawInp = (document.getElementById('apk-staff-search-input')?.value || '').trim().toLowerCase(); const pinVal = (document.getElementById('apk-login-pin')?.value || '').trim(); const errBox = document.getElementById('apk-login-err'); const compStaff = state.employees.filter(e => (e.companyRegId || 'AJSL-2026') === state.companyRegId); const emp = compStaff.find(e => rawInp.includes(e.empId.toLowerCase()) || e.name.toLowerCase().includes(rawInp)); if (!emp || pinVal !== emp.pin) { errBox.textContent = 'Invalid Staff ID or PIN'; errBox.classList.remove('hidden'); return; } errBox.classList.add('hidden'); state.currentEmpId = emp.empId; state.apkLinked = true; state.mobileLoggedIn = true; switchApkTab('punch'); renderApk(); showToast(`Welcome, ${emp.name}!`, '#10b981'); } function handleMobileLogout() { state.mobileLoggedIn = false; renderApk(); } function switchBackToCompanySetup() { state.apkLinked = false; state.mobileLoggedIn = false; renderApk(); } function toggleApkDrawer(show) { document.getElementById('apk-drawer').classList.toggle('hidden', !show); } function switchApkTab(tab) { state.apkTab = tab; ['punch', 'tasks', 'trips', 'leave', 'advance', 'history', 'reports', 'settings'].forEach(t => { document.getElementById('apk-tab-' + t)?.classList.toggle('hidden', t !== tab); }); document.querySelectorAll('.apk-drawer-btn[data-apkdir]').forEach(btn => btn.classList.toggle('active', btn.dataset.apkdir === tab)); renderApk(); } function toggleApkNetwork() { state.apkOnline = !state.apkOnline; const pill = document.getElementById('apk-net-pill'); pill.textContent = state.apkOnline ? 'โ— Online' : 'โ— Offline'; pill.style.color = state.apkOnline ? '#34d399' : '#fbbf24'; if (state.apkOnline && state.offlineQueue.length > 0) syncApkOfflineQueueNow(); renderApk(); } function selectApkBranchLocation(branchId) { const br = state.branches.find(b => b.id === branchId); if (!br) return; state.apkAddress = br.name; state.apkLat = br.lat; state.apkLng = br.lng; renderAll(); } function detectLiveBrowserGps(silent = false) { if (!navigator.geolocation) { if (!silent) showToast('Active Department GPS coordinates locked'); return; } navigator.geolocation.getCurrentPosition(pos => { state.apkLat = Number(pos.coords.latitude.toFixed(5)); state.apkLng = Number(pos.coords.longitude.toFixed(5)); state.apkAddress = `Live GPS (${state.apkLat}, ${state.apkLng})`; renderAll(); }, () => {}); } function toggleFakeGpsSimulation() { state.fakeGpsActive = !state.fakeGpsActive; const btn = document.getElementById('apk-fake-gps-btn'); btn.textContent = state.fakeGpsActive ? '๐Ÿšจ Mock GPS Blocked' : '๐Ÿ›ก๏ธ GPS OK'; btn.style.color = state.fakeGpsActive ? '#e11d48' : '#059669'; } function captureWatermarkedSelfie() { const canvas = document.getElementById('apk-selfie-canvas'); if (!canvas) return; const ctx = canvas.getContext('2d'); ctx.fillStyle = '#1e293b'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = '#38bdf8'; ctx.beginPath(); ctx.arc(58, 25, 11, 0, Math.PI * 2); ctx.fill(); ctx.fillStyle = 'rgba(11, 19, 43, 0.9)'; ctx.fillRect(0, 46, canvas.width, 22); ctx.fillStyle = '#34d399'; ctx.font = 'bold 7.5px monospace'; ctx.fillText(`AI FACE MATCH 98.4%`, 4, 56); state.latestSelfieDataUrl = canvas.toDataURL('image/png'); state.latestFaceScore = '98.4%'; const st = document.getElementById('apk-selfie-status'); st.className = 'badge badge-emerald'; st.textContent = 'โœ“ Face Matched (98.4%)'; } function handleSelfieFileUpload(event) { const file = event.target.files?.[0]; if (!file) return; state.latestFaceScore = '97.8%'; const st = document.getElementById('apk-selfie-status'); st.className = 'badge badge-emerald'; st.textContent = 'โœ“ Face Matched (97.8%)'; } function recordApkVoiceRemark() { state.voiceNoteAttached = true; const inp = document.getElementById('apk-punch-remark'); if (!inp.value.trim()) inp.value = '๐ŸŽ™๏ธ 10s Voice Note: Customer site check completed'; showToast('๐ŸŽ™๏ธ Voice Remark Recorded!', '#10b981'); } function performMobileGpsPunch(forcedType = null) { if (state.fakeGpsActive) { showToast('๐Ÿšจ Fake GPS App Detected! Punch Blocked.', '#e11d48'); return; } const emp = state.employees.find(e => e.empId === state.currentEmpId); if (!emp) return; const rights = emp.rights || getDefaultStaffRights(); if (rights.selfie && !state.latestSelfieDataUrl) captureWatermarkedSelfie(); const nextType = forcedType || (emp.status === 'IN' ? 'PUNCH OUT' : 'PUNCH IN'); emp.status = nextType === 'PUNCH IN' ? 'IN' : 'OUT'; const nowStr = new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' }); const remark = document.getElementById('apk-punch-remark').value.trim() || 'GPS Verified Punch'; const punch = { id: 'P' + Date.now(), companyRegId: state.companyRegId, date: '2026-11-27', empId: emp.empId, empName: emp.name, type: nextType, time: nowStr, isLate: false, lat: state.apkLat, lng: state.apkLng, address: state.apkAddress, selfieUrl: rights.selfie ? state.latestSelfieDataUrl : '', faceScore: rights.selfie ? (state.latestFaceScore || '98.1%') : '', voiceNote: state.voiceNoteAttached, remark }; state.latestSelfieDataUrl = ''; state.voiceNoteAttached = false; document.getElementById('apk-punch-remark').value = ''; if (!state.apkOnline && rights.offlineSync) { state.offlineQueue.push(punch); renderApk(); showToast(`๐Ÿ“ด Saved to Offline Queue (${state.offlineQueue.length})`, '#d97706'); return; } state.punches.unshift(punch); state.selectedPunchId = punch.id; savePersistentState(); renderAll(); showToast(`${nextType} recorded at ${state.apkAddress}`, '#10b981'); } function syncApkOfflineQueueNow() { state.offlineQueue.forEach(item => { state.punches.unshift(item); state.selectedPunchId = item.id; }); state.offlineQueue = []; savePersistentState(); renderAll(); } function triggerApkSosEmergency() { const emp = state.employees.find(e => e.empId === state.currentEmpId); if (!emp) return; state.activeSosAlert = { empName: emp.name, empId: emp.empId, address: state.apkAddress, time: new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' }) }; renderAll(); showToast('๐Ÿšจ SOS EMERGENCY SENT TO COMPANY ADMIN!', '#dc2626'); } function acknowledgeWebSosAlert() { state.activeSosAlert = null; renderAll(); } function completeApkFieldTask(taskId) { const tsk = state.tasks.find(t => t.id === taskId); if (!tsk) return; tsk.status = 'COMPLETED'; savePersistentState(); renderAll(); } function captureOdometerProof() { state.odometerVerified = true; const b = document.getElementById('apk-odo-photo-badge'); b.className = 'badge badge-emerald'; b.textContent = 'โœ“ Meter Photo Attached'; } function startApkFieldTrip() { const emp = state.employees.find(e => e.empId === state.currentEmpId); if (!emp) return; state.activeTrip = { empId: emp.empId, empName: emp.name, vehicle: document.getElementById('apk-trip-vehicle').value, vehicleNo: document.getElementById('apk-trip-vno').value.trim().toUpperCase(), rate: Number(document.getElementById('apk-trip-rate').value) || 4, odoStart: document.getElementById('apk-odo-start').value.trim() || '14220', startTime: new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' }), startPlace: state.apkAddress, startLat: state.apkLat, startLng: state.apkLng }; document.getElementById('apk-btn-start-trip').disabled = true; document.getElementById('apk-btn-end-trip').disabled = false; document.getElementById('apk-trip-status-box').textContent = `โ–ถ Live Route Started at ${state.apkAddress}`; } function endApkFieldTrip() { if (!state.activeTrip) return; const customer = document.getElementById('apk-trip-customer').value.trim() || 'Client Site Visit'; const km = 4.5; const amount = Math.round(km * state.activeTrip.rate); state.trips.unshift({ id: 'T' + Date.now(), companyRegId: state.companyRegId, date: '2026-11-27', empId: state.activeTrip.empId, empName: state.activeTrip.empName, vehicle: state.activeTrip.vehicle, vehicleNo: state.activeTrip.vehicleNo, rate: state.activeTrip.rate, startPlace: state.activeTrip.startPlace, endPlace: state.apkAddress, odoStart: state.activeTrip.odoStart, odoEnd: document.getElementById('apk-odo-end').value.trim() || '14225', km, amount, customer }); state.expenses.unshift({ id: 'E' + Date.now(), companyRegId: state.companyRegId, date: '2026-11-27', empId: state.activeTrip.empId, empName: state.activeTrip.empName, category: 'Petrol / Conveyance', note: `${state.activeTrip.startPlace} โ†’ ${state.apkAddress} โ€ข ${km} km`, amount }); state.activeTrip = null; document.getElementById('apk-btn-start-trip').disabled = false; document.getElementById('apk-btn-end-trip').disabled = true; savePersistentState(); renderAll(); showToast(`โœ“ Trip Synced: ${km} km โ€ข โ‚น${amount}`, '#10b981'); } function captureApkExpenseBillPhoto() { state.billPhotoAttached = true; showToast('๐Ÿงพ Bill Photo Attached!', '#10b981'); } function submitApkFieldExpense() { const emp = state.employees.find(e => e.empId === state.currentEmpId); const amt = Number(document.getElementById('apk-exp-amt').value); const note = document.getElementById('apk-exp-note').value.trim() || 'Field Petrol Bill'; if (!emp || !amt || amt <= 0) { showToast('Enter valid Expense Amount!', '#e11d48'); return; } state.expenses.unshift({ id: 'E' + Date.now(), companyRegId: state.companyRegId, date: '2026-11-27', empId: emp.empId, empName: emp.name, category: document.getElementById('apk-exp-cat').value, note, amount: amt }); document.getElementById('apk-exp-amt').value = ''; savePersistentState(); renderAll(); } function submitApkLeaveRequest() { const emp = state.employees.find(e => e.empId === state.currentEmpId); const reason = document.getElementById('apk-leave-reason').value.trim(); if (!emp || !reason) { showToast('Enter leave reason!', '#e11d48'); return; } state.leaves.unshift({ id: 'L' + Date.now(), companyRegId: state.companyRegId, date: document.getElementById('apk-leave-date').value, empId: emp.empId, empName: emp.name, leaveType: document.getElementById('apk-leave-type').value, reason, status: 'PENDING' }); document.getElementById('apk-leave-reason').value = ''; savePersistentState(); renderAll(); } function submitApkOtOrRegularize(kind) { const emp = state.employees.find(e => e.empId === state.currentEmpId); if (!emp) return; state.leaves.unshift({ id: 'L' + Date.now(), companyRegId: state.companyRegId, date: '2026-11-27', empId: emp.empId, empName: emp.name, leaveType: kind === 'OT' ? 'โณ OT Claim' : '๐Ÿ”„ Regularization', reason: 'Submitted from APK', status: 'PENDING' }); savePersistentState(); renderAll(); } function submitApkSalaryAdvance() { const emp = state.employees.find(e => e.empId === state.currentEmpId); const amt = Number(document.getElementById('apk-adv-amt').value); const reason = document.getElementById('apk-adv-reason').value.trim(); if (!emp || !amt || !reason) { showToast('Enter Amount & Reason!', '#e11d48'); return; } state.salaryAdvances.unshift({ id: 'ADV' + Date.now(), companyRegId: state.companyRegId, date: document.getElementById('apk-adv-date').value, empId: emp.empId, empName: emp.name, amount: amt, reason, status: 'PENDING' }); document.getElementById('apk-adv-amt').value = ''; document.getElementById('apk-adv-reason').value = ''; savePersistentState(); renderAll(); } function initApkSignPad() { const canvas = document.getElementById('apk-sign-canvas'); if (!canvas) return; const ctx = canvas.getContext('2d'); let drawing = false; canvas.addEventListener('mousedown', e => { drawing = true; state.hasSignature = true; const r = canvas.getBoundingClientRect(); ctx.beginPath(); ctx.moveTo(e.clientX - r.left, e.clientY - r.top); }); canvas.addEventListener('mousemove', e => { if (!drawing) return; const r = canvas.getBoundingClientRect(); ctx.lineTo(e.clientX - r.left, e.clientY - r.top); ctx.stroke(); }); window.addEventListener('mouseup', () => { drawing = false; }); } function clearApkSignPad() { const canvas = document.getElementById('apk-sign-canvas'); if (canvas) canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height); } function printApkSelfReport() { const emp = state.employees.find(e => e.empId === state.currentEmpId); if (!emp) return; const mine = state.punches.filter(p => p.empId === emp.empId); openInAppPrintPreview(`${emp.name} โ€” Personal Report`, `

${escapeHtmlSafe(state.companyName)} โ€” ${escapeHtmlSafe(emp.name)}

${mine.map(p => ``).join('')}
Date & TimePunchLocation
${p.date} ${p.time}${p.type}${p.address}
`); } function downloadApkSelfReport() { printApkSelfReport(); downloadCurrentModalHtml(); } function saveApkStandaloneWhatsAppConfig() { state.apkStandaloneWa.configured = true; savePersistentState(); showToast('๐Ÿ’ฌ CPaaSLink API Saved!', '#10b981'); } function sendApkStandaloneWhatsAppReport() { showToast('๐Ÿ“ฒ Report Sent via CPaaSLink WhatsApp API!', '#10b981'); } function renderApk() { document.getElementById('apk-setup-screen')?.classList.toggle('hidden', state.apkLinked); document.getElementById('apk-login-screen')?.classList.toggle('hidden', !state.apkLinked || state.mobileLoggedIn); document.getElementById('apk-main-screen')?.classList.toggle('hidden', !state.apkLinked || !state.mobileLoggedIn); if (!state.apkLinked) handleApkCompanySearchInput(document.getElementById('apk-company-name-input')?.value || ''); document.getElementById('apk-login-reg-badge').textContent = state.companyRegId; document.getElementById('apk-login-comp-title').textContent = state.companyName; document.getElementById('apk-top-comp-name').textContent = state.companyName; document.getElementById('apk-set-comp').textContent = state.companyName; document.getElementById('apk-set-regid').textContent = state.companyRegId; const compBranches = state.branches.filter(b => (b.companyRegId || 'AJSL-2026') === state.companyRegId); const brSel = document.getElementById('apk-branch-select'); if (brSel) brSel.innerHTML = (compBranches.length ? compBranches : state.branches).map(b => ``).join(''); const compStaff = state.employees.filter(e => (e.companyRegId || 'AJSL-2026') === state.companyRegId); const emp = compStaff.find(e => e.empId === state.currentEmpId) || compStaff[0]; if (emp) { document.getElementById('apk-top-staff-name').textContent = `${emp.name} (${emp.empId})`; const isIn = emp.status === 'IN'; document.getElementById('apk-punch-in-btn').disabled = isIn; document.getElementById('apk-punch-out-btn').disabled = !isIn; const myPunches = state.punches.filter(p => p.empId === emp.empId); const lastIn = myPunches.find(p => p.type === 'PUNCH IN'); const lastOut = myPunches.find(p => p.type === 'PUNCH OUT'); document.getElementById('apk-in-time').textContent = lastIn ? lastIn.time : '--:--'; document.getElementById('apk-in-place').textContent = lastIn ? lastIn.address : 'Not punched in'; document.getElementById('apk-out-time').textContent = lastOut ? lastOut.time : '--:--'; document.getElementById('apk-out-place').textContent = lastOut ? lastOut.address : 'Not punched out'; document.getElementById('apk-today-punches-list').innerHTML = myPunches.map(p => `
${p.type} โ€ข ${p.time}
${p.address}
`).join(''); document.getElementById('apk-my-rep-list').innerHTML = myPunches.map(p => `
${p.type} โ€ข ${p.date} ${p.time}
`).join(''); } document.getElementById('apk-gps-coords').textContent = `${state.apkLat.toFixed(5)}, ${state.apkLng.toFixed(5)} (ยฑ12m)`; document.getElementById('apk-gps-address').textContent = state.apkAddress; } /* ================= TIER 2: COMPANY ADMIN CONSOLE ================= */ function switchWebLoginMode(mode) { state.webLoginMode = mode; document.getElementById('web-tab-pass-btn')?.classList.toggle('active', mode === 'PASSWORD'); document.getElementById('web-tab-otp-btn')?.classList.toggle('active', mode === 'OTP'); document.getElementById('web-login-pass-fields')?.classList.toggle('hidden', mode !== 'PASSWORD'); document.getElementById('web-login-otp-fields')?.classList.toggle('hidden', mode !== 'OTP'); } function sendWebAdminSmsOtp() { const mob = (document.getElementById('web-login-mobile')?.value || '').trim(); if (!mob) { showToast('Enter Registered Admin Mobile Number!', '#e11d48'); return; } state.webGeneratedOtp = '123456'; showToast(`๐Ÿ“ฒ SMS OTP Sent to ${mob} (Demo OTP: 123456)`, '#10b981'); } function syncWebLoginCompanyByRegId(val) { const q = (val || '').trim().toLowerCase(); if (!q) return; const found = state.registeredCompanies.find(c => c.regId.toLowerCase() === q || (c.email || '').toLowerCase() === q); if (found) activateRegisteredCompany(found.regId, false); } function activateLicenseKeyFromLogin() { const keyInp = (document.getElementById('web-login-unlock-key')?.value || '').trim().toUpperCase(); const comp = state.registeredCompanies.find(c => c.regId === state.companyRegId); if (!comp || !keyInp || keyInp !== (comp.licenseSerial || '').toUpperCase()) { showToast('โŒ Invalid License Serial Key!', '#e11d48'); return; } if (computeRemainingDays(comp.licenseExpiry) <= 0) { const months = comp.licenseMonths || 12; comp.licenseStart = formatIsoDateOffset(0); comp.licenseExpiry = formatIsoDateOffset(months * 30); } comp.active = true; savePersistentState(); renderWeb(); showToast(`๐Ÿ”‘ License Activated! Valid till ${comp.licenseExpiry}`, '#10b981'); } function handleWebLogin() { const errBox = document.getElementById('web-login-err'); let matchedComp = null; if (!state.webCompanyBound) { const regInput = (document.getElementById('web-login-regid')?.value || '').trim().toLowerCase(); matchedComp = state.registeredCompanies.find(c => c.regId.toLowerCase() === regInput || (c.email || '').toLowerCase() === regInput); if (!matchedComp) { errBox.textContent = 'Invalid Company Registration ID or Company Email!'; errBox.classList.remove('hidden'); return; } } else { matchedComp = state.registeredCompanies.find(c => c.regId === state.companyRegId); } if (!matchedComp) return; activateRegisteredCompany(matchedComp.regId, false); const daysLeft = computeRemainingDays(matchedComp.licenseExpiry); if (daysLeft <= 0 || matchedComp.active === false) { errBox.textContent = `โ›” License Expired on ${matchedComp.licenseExpiry}! Enter valid License Key above.`; errBox.classList.remove('hidden'); return; } if (state.webLoginMode === 'OTP') { const otpEntered = (document.getElementById('web-login-otp-code')?.value || '').trim(); if (otpEntered !== state.webGeneratedOtp && otpEntered !== '123456') { errBox.textContent = 'Invalid 6-Digit SMS OTP!'; errBox.classList.remove('hidden'); return; } state.webAdminEmail = matchedComp.email; } else { const email = (document.getElementById('web-login-email')?.value || '').trim().toLowerCase(); const pass = (document.getElementById('web-login-pass')?.value || '').trim(); if ((matchedComp.email || '').toLowerCase() !== email || (matchedComp.password || 'admin123') !== pass) { errBox.textContent = 'Invalid Admin Email or Password!'; errBox.classList.remove('hidden'); return; } state.webAdminEmail = email; } errBox.classList.add('hidden'); state.webCompanyBound = true; try { localStorage.setItem(WEB_BOUND_REG_KEY, matchedComp.regId); } catch (e) {} state.webLoggedIn = true; savePersistentState(); renderWeb(); showToast(`Signed in to ${state.companyName} Console!`, '#10b981'); } function handleWebLogout() { state.webLoggedIn = false; renderWeb(); } function toggleWebDrawer(forceState) { const sb = document.getElementById('web-sidebar'); const bd = document.getElementById('web-drawer-backdrop'); if (!sb) return; if (window.innerWidth <= 1280) { const nextOpen = typeof forceState === 'boolean' ? forceState : !sb.classList.contains('drawer-open'); sb.classList.toggle('drawer-open', nextOpen); if (bd) bd.classList.toggle('hidden', !nextOpen); } else { const nextCollapsed = typeof forceState === 'boolean' ? !forceState : !sb.classList.contains('sidebar-collapsed'); sb.classList.toggle('sidebar-collapsed', nextCollapsed); } } function toggleReportsSubmenu() { const sub = document.getElementById('web-reports-submenu'); if (sub) sub.classList.toggle('hidden'); } function openReportSubMenu(subType, closeDrawer = false) { state.webReportSubType = subType; const sel = document.getElementById('rep-type-filter'); if (sel) sel.value = subType; switchWebMenu('reports', closeDrawer, true); renderWeb(); } function toggleStaffDetailSubmenu() { const sub = document.getElementById('web-staff-submenu'); if (sub) sub.classList.toggle('hidden'); } function openStaffDetailSubMenu(subMenuKey) { switchWebMenu(subMenuKey, true, true); } function toggleWebCommSubmenu() { const sub = document.getElementById('web-comm-submenu'); if (sub) sub.classList.toggle('hidden'); } function openWebCommSubMenu(subKey, closeDrawer = false) { state.webCommSubTab = subKey; ['wa', 'sms', 'email'].forEach(k => document.getElementById('web-comm-card-' + k)?.classList.toggle('hidden', k !== subKey)); switchWebMenu('comm', closeDrawer, true); } function saveWebCommConfig(kind) { showToast(`Saved ${kind.toUpperCase()} API!`, '#10b981'); } function testWebCommConfig(kind) { showToast(`Tested ${kind.toUpperCase()} API!`, '#10b981'); } function switchWebMenu(menu, closeDrawer = true) { state.webMenu = menu; ['live', 'tasks', 'trips', 'leaves', 'expenses', 'payroll', 'advances', 'reports', 'holidays', 'branches', 'rights', 'company', 'compprofile', 'settings', 'comm', 'license', 'support'].forEach(m => { document.getElementById('web-panel-' + m)?.classList.toggle('hidden', m !== menu); }); document.querySelectorAll('.v-sb-btn[data-webmenu]').forEach(btn => { btn.classList.toggle('active', btn.dataset.webmenu === menu); }); if (closeDrawer && window.innerWidth <= 1280) toggleWebDrawer(false); } function verifyCompanyLicenseKey() { const inp = (document.getElementById('web-lic-verify-input')?.value || '').trim().toUpperCase(); const comp = state.registeredCompanies.find(c => c.regId === state.companyRegId); if (!comp) return; if (comp.licenseActivated) { showToast('๐Ÿ”’ License is already activated and locked!', '#0b132b'); return; } if (!inp || inp !== (comp.licenseSerial || '').toUpperCase()) { showToast('โŒ Invalid License Key! Check key issued in Master Console.', '#e11d48'); return; } const m = comp.licenseMonths || 12; if (computeRemainingDays(comp.licenseExpiry) <= 0) { comp.licenseStart = formatIsoDateOffset(0); comp.licenseExpiry = formatIsoDateOffset(m * 30); } comp.active = true; comp.licenseActivated = true; clearDemoDataForFreshCompany(comp.regId); savePersistentState(); renderAll(); const rem = computeRemainingDays(comp.licenseExpiry); showToast(`โœ… License Activated! Demo data erased & Company Profile locked (${rem} Days Valid)`, '#10b981'); } function updateAdvanceStatus(advId, status) { const adv = state.salaryAdvances.find(a => a.id === advId); if (adv) { adv.status = status; savePersistentState(); renderAll(); } } function issueDirectSalaryAdvance() { const empId = document.getElementById('web-adv-staff-sel').value; const emp = state.employees.find(e => e.empId === empId); const amt = Number(document.getElementById('web-adv-amt-inp').value); const reason = document.getElementById('web-adv-note-inp').value.trim() || 'Direct HR Advance'; if (!emp || !amt || amt <= 0) return; state.salaryAdvances.unshift({ id: 'ADV' + Date.now(), companyRegId: state.companyRegId, date: '2026-11-27', empId: emp.empId, empName: emp.name, amount: amt, reason, status: 'APPROVED' }); document.getElementById('web-adv-amt-inp').value = ''; savePersistentState(); renderAll(); } function assignStaffDepartment(empId, deptId) { const emp = state.employees.find(e => e.empId === empId); if (emp) { emp.deptId = deptId; savePersistentState(); renderAll(); } } function addTenantBranch() { const name = document.getElementById('br-name-input').value.trim(); if (!name) return; state.branches.push({ id: 'BR' + Date.now(), companyRegId: state.companyRegId, name, shift: document.getElementById('br-shift-input').value, lead: document.getElementById('br-lead-input').value, lat: 13.0827, lng: 80.2707 }); document.getElementById('br-name-input').value = ''; savePersistentState(); renderAll(); } function deleteTenantBranch(id) { state.branches = state.branches.filter(b => b.id !== id); savePersistentState(); renderAll(); } function toggleStaffFeatureRight(empId, rightKey, checked) { const emp = state.employees.find(e => e.empId === empId); if (emp) { emp.rights[rightKey] = checked; savePersistentState(); renderAll(); } } function applyStaffRightsPreset(empId, preset) { const emp = state.employees.find(e => e.empId === empId); if (!emp) return; emp.rights = preset === 'ALL' ? getDefaultStaffRights() : { ...getDefaultStaffRights(), trips: false, expenseEntry: false, salaryAdvance: false, leave: false }; savePersistentState(); renderAll(); } function selectStaffProfileRow(empId) { state.selectedProfileEmpId = empId; renderWeb(); } function openEditStaffProfileModal() { const emp = state.employees.find(e => e.empId === state.selectedProfileEmpId); if (!emp) return; document.getElementById('edit-sp-name').value = emp.name || ''; document.getElementById('edit-sp-role').value = emp.role || ''; document.getElementById('edit-sp-phone').value = emp.phone || ''; document.getElementById('edit-sp-blood').value = emp.bloodGroup || 'O+ve'; document.getElementById('edit-sp-aadhaar').value = emp.aadhaar || ''; document.getElementById('edit-sp-pan').value = emp.pan || ''; document.getElementById('edit-sp-relation').value = emp.relationType || 'Wife'; document.getElementById('edit-sp-relname').value = emp.emergencyName || ''; document.getElementById('edit-sp-relphone').value = emp.emergencyPhone || ''; document.getElementById('edit-sp-pin').value = emp.pin || '1234'; document.getElementById('edit-sp-address').value = emp.address || ''; document.getElementById('edit-staff-profile-box').classList.remove('hidden'); } function saveEditedStaffProfile() { const emp = state.employees.find(e => e.empId === state.selectedProfileEmpId); if (!emp) return; emp.name = document.getElementById('edit-sp-name').value.trim() || emp.name; emp.role = document.getElementById('edit-sp-role').value.trim(); emp.phone = document.getElementById('edit-sp-phone').value.trim(); emp.bloodGroup = document.getElementById('edit-sp-blood').value; emp.aadhaar = document.getElementById('edit-sp-aadhaar').value.trim(); emp.pan = document.getElementById('edit-sp-pan').value.trim().toUpperCase(); emp.relationType = document.getElementById('edit-sp-relation').value; emp.emergencyName = document.getElementById('edit-sp-relname').value.trim(); emp.emergencyPhone = document.getElementById('edit-sp-relphone').value.trim(); emp.pin = document.getElementById('edit-sp-pin').value.trim() || '1234'; emp.address = document.getElementById('edit-sp-address').value.trim(); document.getElementById('edit-staff-profile-box').classList.add('hidden'); savePersistentState(); renderAll(); } function createStaffFromCompanyProfile() { const empId = document.getElementById('comp-new-staff-id').value.trim().toUpperCase(); const name = document.getElementById('comp-new-staff-name').value.trim(); if (!empId || !name) { showToast('Enter Staff ID and Name!', '#e11d48'); return; } state.employees.push({ empId, companyRegId: state.companyRegId, name, role: document.getElementById('comp-new-staff-role').value.trim() || 'Field Staff', phone: document.getElementById('comp-new-staff-phone').value.trim(), aadhaar: document.getElementById('comp-new-staff-aadhaar').value.trim(), pan: document.getElementById('comp-new-staff-pan').value.trim().toUpperCase(), bloodGroup: document.getElementById('comp-new-staff-blood').value, address: document.getElementById('comp-new-staff-address').value.trim(), relationType: document.getElementById('comp-new-staff-relation').value, emergencyName: document.getElementById('comp-new-staff-relname').value.trim(), emergencyPhone: document.getElementById('comp-new-staff-relphone').value.trim(), pin: document.getElementById('comp-new-staff-pin').value.trim() || '1234', status: 'OUT', rights: getDefaultStaffRights() }); state.selectedProfileEmpId = empId; savePersistentState(); renderAll(); showToast(`โœ… Saved Staff Profile ${empId} (${name})!`, '#10b981'); } function printStaffProfilesDocument(mode = 'SINGLE', empId = null) { const compStaff = state.employees.filter(e => (e.companyRegId || 'AJSL-2026') === state.companyRegId); const list = mode === 'ALL' ? compStaff : compStaff.filter(e => e.empId === (empId || state.selectedProfileEmpId)); const cardsHtml = getCompanyPrintHeaderHtml(mode === 'ALL' ? 'ALL STAFF KYC DIRECTORY' : 'EMPLOYEE KYC PROFILE') + list.map((e, idx) => `
#${idx + 1} ${escapeHtmlSafe(e.name)} (${escapeHtmlSafe(e.empId)}) โ€” ${escapeHtmlSafe(e.role)}
Mobile${escapeHtmlSafe(e.phone || 'โ€”')}Blood Group${escapeHtmlSafe(e.bloodGroup || 'O+ve')}
Aadhaar${escapeHtmlSafe(e.aadhaar || 'โ€”')}PAN${escapeHtmlSafe(e.pan || 'โ€”')}
Emergency Contact${escapeHtmlSafe(e.emergencyName || 'โ€”')} (${escapeHtmlSafe(e.relationType || 'Family')})Emergency Phone${escapeHtmlSafe(e.emergencyPhone || 'โ€”')}
Address${escapeHtmlSafe(e.address || 'โ€”')}
`).join(''); openInAppPrintPreview(mode === 'ALL' ? `${state.companyName} โ€” All Staff Profiles` : `${list[0]?.name} โ€” Staff Profile`, cardsHtml); } function downloadStaffProfilesPdf(mode = 'SINGLE', empId = null) { printStaffProfilesDocument(mode, empId); downloadCurrentModalHtml(); } function raiseTenantSupportTicket() { const subject = document.getElementById('web-tkt-subject').value.trim(); const details = document.getElementById('web-tkt-details').value.trim(); if (!subject || !details) return; state.supportTickets.unshift({ id: 'TKT-' + Math.floor(1000 + Math.random() * 9000), companyRegId: state.companyRegId, companyName: state.companyName, date: '2026-11-27', category: document.getElementById('web-tkt-category').value || 'Support', priority: document.getElementById('web-tkt-priority').value, subject, details, status: 'OPEN', masterReply: '' }); document.getElementById('web-tkt-subject').value = ''; document.getElementById('web-tkt-details').value = ''; savePersistentState(); renderAll(); } function assignFieldTaskToStaff() { const empId = document.getElementById('task-staff-select').value; const emp = state.employees.find(e => e.empId === empId); const client = document.getElementById('task-client-input').value.trim(); if (!emp || !client) return; state.tasks.unshift({ id: 'TSK' + Date.now(), companyRegId: state.companyRegId, date: '2026-11-27', empId: emp.empId, empName: emp.name, client, clientPhone: document.getElementById('task-phone-input').value.trim(), clientAddress: document.getElementById('task-address-input').value.trim(), note: document.getElementById('task-note-input').value.trim(), status: 'PENDING' }); savePersistentState(); renderAll(); } function printFieldTasksSheet(mode = 'ALL', taskId = null) { const compTasks = state.tasks.filter(tk => (tk.companyRegId || 'AJSL-2026') === state.companyRegId); const list = mode === 'SINGLE' ? compTasks.filter(t => t.id === taskId) : compTasks; const rows = list.map(t => `${t.date}${escapeHtmlSafe(t.empName)}${escapeHtmlSafe(t.client)} (${escapeHtmlSafe(t.clientPhone)})${escapeHtmlSafe(t.clientAddress)}${escapeHtmlSafe(t.note)}`).join(''); openInAppPrintPreview(`${state.companyName} โ€” Field Job Sheet`, `${getCompanyPrintHeaderHtml('CUSTOMER FIELD JOB SHEET')}${rows}
DateStaffCustomerAddressNote
`); } function downloadFieldTasksPdf(mode = 'ALL', taskId = null) { printFieldTasksSheet(mode, taskId); downloadCurrentModalHtml(); } function addTenantHoliday() { const date = document.getElementById('hol-date-input').value; const name = document.getElementById('hol-name-input').value.trim(); if (!date || !name) return; state.holidays.unshift({ id: 'H' + Date.now(), companyRegId: state.companyRegId, date, name, type: 'Public Holiday' }); savePersistentState(); renderAll(); } function deleteTenantHoliday(id) { state.holidays = state.holidays.filter(h => h.id !== id); savePersistentState(); renderAll(); } function updateLeaveStatus(leaveId, newStatus) { const lv = state.leaves.find(l => l.id === leaveId); if (lv) { lv.status = newStatus; savePersistentState(); renderAll(); } } function addWebPetrolExpense() { const empId = document.getElementById('web-exp-staff-sel').value; const emp = state.employees.find(e => e.empId === empId); const amount = Number(document.getElementById('web-exp-amt-inp').value); if (!emp || !amount || amount <= 0) return; state.expenses.unshift({ id: 'E' + Date.now(), companyRegId: state.companyRegId, date: '2026-11-27', empId: emp.empId, empName: emp.name, category: document.getElementById('web-exp-cat-sel').value, note: document.getElementById('web-exp-note-inp').value || 'Field Petrol', amount }); document.getElementById('web-exp-amt-inp').value = ''; savePersistentState(); renderAll(); } function exportCompanyCsv(kind) { const rows = [['Date', 'Time', 'Staff ID', 'Staff Name', 'Type', 'Address'], ...state.punches.map(p => [p.date, p.time, p.empId, p.empName, p.type, p.address])]; const csv = rows.map(r => r.map(v => `"${String(v ?? '').replace(/"/g, '""')}"`).join(',')).join('\n'); const a = document.createElement('a'); a.href = URL.createObjectURL(new Blob([csv], { type: 'text/csv;charset=utf-8;' })); a.download = `${state.companyRegId}_${kind}_Export.csv`; a.click(); } function renderWeb() { const comp = state.registeredCompanies.find(c => c.regId === state.companyRegId); const daysLeft = comp ? computeRemainingDays(comp.licenseExpiry) : 365; const isExpired = daysLeft <= 0 || (comp && comp.active === false); // Hide Company Registration ID input once bound on first login (no Bound badge shown) const regGroup = document.getElementById('web-login-regid-group'); if (regGroup) regGroup.classList.toggle('hidden', !!state.webCompanyBound); updateWebSyncIndicator(); const loginLockBox = document.getElementById('web-login-expired-lock'); if (comp && loginLockBox) { loginLockBox.classList.toggle('hidden', !isExpired); } if (state.webLoggedIn && isExpired) state.webLoggedIn = false; document.getElementById('web-login-screen').classList.toggle('hidden', state.webLoggedIn); document.getElementById('web-dashboard-screen').classList.toggle('hidden', !state.webLoggedIn); const webHeaderLogo = document.getElementById('web-header-logo-badge'); if (webHeaderLogo) { webHeaderLogo.innerHTML = state.companyLogoUrl ? `Logo` : escapeHtmlSafe(state.logoInitials || 'AJ'); } document.getElementById('web-sb-comp-title').textContent = state.companyName; document.getElementById('web-top-regid-badge').textContent = 'ID: ' + state.companyRegId; // Update Read-Only Company Profile View in Company Console const cpLogoBox = document.getElementById('cp-view-logo-box'); if (cpLogoBox) { cpLogoBox.innerHTML = state.companyLogoUrl ? `Company Logo` : escapeHtmlSafe(state.logoInitials || 'AJ'); } const cpName = document.getElementById('cp-view-name'); if (cpName) cpName.textContent = state.companyName; const cpReg1 = document.getElementById('cp-view-regid'); if (cpReg1) cpReg1.textContent = state.companyRegId; const cpAddr = document.getElementById('cp-view-address'); if (cpAddr) cpAddr.textContent = state.companyAddress || 'โ€”'; const cpReg2 = document.getElementById('cp-view-regid-val'); if (cpReg2) cpReg2.textContent = state.companyRegId; const cpGst = document.getElementById('cp-view-gst-val'); if (cpGst) cpGst.textContent = state.companyGst || 'Not Provided'; const cpEmail = document.getElementById('cp-view-email-val'); if (cpEmail) cpEmail.textContent = state.companyEmail || 'โ€”'; const cpPhone = document.getElementById('cp-view-phone-val'); if (cpPhone) cpPhone.textContent = state.companyPhone || 'โ€”'; if (comp) { const isActivated = !!comp.licenseActivated; document.getElementById('web-lic-serial-val').textContent = isActivated ? comp.licenseSerial : 'PENDING ACTIVATION (TRIAL)'; document.getElementById('web-lic-months-val').textContent = `${comp.licenseMonths || 12} Months`; document.getElementById('web-lic-expiry-val').textContent = comp.licenseExpiry || '2027-11-26'; document.getElementById('web-lic-days-val').textContent = isActivated ? (daysLeft > 0 ? `${daysLeft} Days Remaining` : 'EXPIRED') : 'Activate Key to Unlock'; const actCard = document.getElementById('web-lic-activation-card'); const lockBan = document.getElementById('web-lic-locked-banner'); const subHint = document.getElementById('web-lic-sub-hint'); if (actCard) actCard.classList.toggle('hidden', isActivated); if (lockBan) lockBan.classList.toggle('hidden', !isActivated); if (subHint) { subHint.textContent = isActivated ? 'License Key activated & locked. Demo data erased; live production workspace active.' : 'Currently in Trial Demo Mode. Activate your License Key below to erase demo data & start live production.'; } const licPill = document.getElementById('web-lic-status-pill'); licPill.className = 'badge ' + (isActivated ? (daysLeft > 0 ? 'badge-emerald' : 'badge-rose') : 'badge-amber'); licPill.textContent = isActivated ? (daysLeft > 0 ? `๐Ÿ”’ ACTIVATED & LOCKED (${daysLeft} DAYS)` : 'โ›” LICENSE EXPIRED') : 'โ— TRIAL DEMO MODE'; document.getElementById('web-lic-expired-banner').classList.toggle('hidden', daysLeft > 0); } const compStaff = state.employees.filter(e => (e.companyRegId || 'AJSL-2026') === state.companyRegId); const compPunches = state.punches.filter(p => (p.companyRegId || 'AJSL-2026') === state.companyRegId); const compTrips = state.trips.filter(t => (t.companyRegId || 'AJSL-2026') === state.companyRegId); const compExp = state.expenses.filter(ex => (ex.companyRegId || 'AJSL-2026') === state.companyRegId); const compLeaves = state.leaves.filter(lv => (lv.companyRegId || 'AJSL-2026') === state.companyRegId); const compTasks = state.tasks.filter(tk => (tk.companyRegId || 'AJSL-2026') === state.companyRegId); const compBranches = state.branches.filter(br => (br.companyRegId || 'AJSL-2026') === state.companyRegId); const compHolidays = state.holidays.filter(hl => (hl.companyRegId || 'AJSL-2026') === state.companyRegId); const compTickets = state.supportTickets.filter(tk => (tk.companyRegId || 'AJSL-2026') === state.companyRegId); const compAdvances = state.salaryAdvances.filter(ad => (ad.companyRegId || 'AJSL-2026') === state.companyRegId); const staffFilterOpts = '' + compStaff.map(e => ``).join(''); ['web-trips-staff-filter', 'web-exp-print-staff-filter', 'web-adv-print-staff-filter'].forEach(selId => { const el = document.getElementById(selId); if (el) { const prev = el.value; el.innerHTML = staffFilterOpts; if (prev) el.value = prev; } }); document.getElementById('web-kpi-staff').textContent = compStaff.length; document.getElementById('web-kpi-punches').textContent = compPunches.length; document.getElementById('web-kpi-branches').textContent = compBranches.length; document.getElementById('web-kpi-km').textContent = compTrips.reduce((s, t) => s + Number(t.km || 0), 0).toFixed(1) + ' km'; const totalExpAmt = compExp.reduce((s, e) => s + Number(e.amount || 0), 0); document.getElementById('web-kpi-exp').textContent = 'โ‚น' + totalExpAmt; document.getElementById('web-exp-total-badge').textContent = 'Total: โ‚น' + totalExpAmt; document.getElementById('web-punches-tbody').innerHTML = compPunches.map(p => ` ${p.empName}
${p.empId}
${p.type} ${p.time} ${p.address} ๐Ÿค– ${p.faceScore || '98%'} `).join(''); document.getElementById('web-trips-tbody').innerHTML = compTrips.map(t => ` ${t.empName} (${t.vehicle}) ${t.startPlace} ${t.endPlace} ${t.km} km โ‚น${t.amount} `).join(''); document.getElementById('web-expenses-tbody').innerHTML = compExp.map(e => ` ${e.date} โ€ข ${e.empName} ${e.category} ${e.note} โ‚น${e.amount} `).join(''); document.getElementById('web-advances-tbody').innerHTML = compAdvances.map(a => ` ${a.date} ${a.empName} โ‚น${a.amount} ${a.reason} ${a.status} `).join(''); ['task-staff-select', 'web-exp-staff-sel', 'web-adv-staff-sel', 'pay-staff-select'].forEach(selId => { const el = document.getElementById(selId); if (el) { const prev = el.value; el.innerHTML = compStaff.map(e => ``).join(''); if (prev) el.value = prev; } }); document.getElementById('web-tasks-tbody').innerHTML = compTasks.map(t => `${t.date}${t.empName}${t.client}${t.clientAddress}${t.note}${t.status}`).join(''); document.getElementById('web-leaves-tbody').innerHTML = compLeaves.map(l => `${l.date}${l.empName}${l.leaveType}${l.reason}${l.status}`).join(''); document.getElementById('web-holidays-tbody').innerHTML = compHolidays.map(h => `${h.date}${h.name}${h.type}`).join(''); document.getElementById('web-branches-tbody').innerHTML = compBranches.map(b => `${b.name}${b.shift}${b.lead}${compStaff.filter(s=>s.deptId===b.id).length} Staff`).join(''); document.getElementById('web-dept-staff-tbody').innerHTML = compStaff.map(s => `${s.empId} โ€” ${s.name}${s.role}${s.shiftWindow || '09:30 AM - 06:30 PM'}`).join(''); document.getElementById('web-tickets-tbody').innerHTML = compTickets.map(tk => `${tk.id}${tk.category}${tk.subject}${tk.status}${tk.masterReply || 'Pending'}`).join(''); const profEmp = compStaff.find(e => e.empId === state.selectedProfileEmpId) || compStaff[0]; if (profEmp) { state.selectedProfileEmpId = profEmp.empId; document.getElementById('sp-name').textContent = profEmp.name; document.getElementById('sp-empid').textContent = profEmp.empId; document.getElementById('sp-phone').textContent = profEmp.phone || 'โ€”'; document.getElementById('sp-aadhaar').textContent = profEmp.aadhaar || 'โ€”'; document.getElementById('sp-pan').textContent = profEmp.pan || 'โ€”'; document.getElementById('sp-emergency').textContent = `${profEmp.emergencyName || 'โ€”'} (${profEmp.relationType || 'Family'}) โ€ข ${profEmp.emergencyPhone || 'โ€”'}`; document.getElementById('sp-address').textContent = profEmp.address || 'โ€”'; } document.getElementById('comp-staff-list-tbody').innerHTML = compStaff.map(e => ` ${e.empId} ${e.name} ${e.role} ${e.aadhaar || 'โ€”'} / ${e.pan || 'โ€”'} ${e.emergencyName || 'โ€”'} ${e.address || 'โ€”'} `).join(''); const repStaffSel = document.getElementById('rep-staff-filter'); if (repStaffSel) { const prev = repStaffSel.value; repStaffSel.innerHTML = staffFilterOpts; if (prev) repStaffSel.value = prev; } const selRepType = document.getElementById('rep-type-filter')?.value || state.webReportSubType || 'PUNCH'; document.getElementById('rep-section-punch').classList.toggle('hidden', selRepType !== 'PUNCH'); document.getElementById('rep-section-field').classList.toggle('hidden', selRepType !== 'FIELD_VISIT'); document.getElementById('rep-section-petrol').classList.toggle('hidden', selRepType !== 'PETROL'); document.getElementById('web-report-tbody').innerHTML = compPunches.map(p => `${p.date} ${p.time}${p.empId} โ€” ${p.empName}${p.type}${p.address}${p.remark}`).join(''); document.getElementById('web-report-trips-tbody').innerHTML = compTrips.map(t => `${t.date} ${t.empName}${t.vehicle}${t.startPlace}${t.endPlace}${t.km} km${t.customer}`).join(''); document.getElementById('web-report-exp-tbody').innerHTML = compExp.map(ex => `${ex.date} ${ex.empName}${ex.category}${ex.note}โ‚น${ex.amount}`).join(''); } /* ================= TIER 3: MASTER SUPER-ADMIN CONSOLE ================= */ function toggleMasterForgotBox() { document.getElementById('master-forgot-box')?.classList.toggle('hidden'); } function resetMasterPasswordNow() { const otp = (document.getElementById('master-reset-otp')?.value || '').trim(); const newPass = (document.getElementById('master-reset-newpass')?.value || '').trim(); if (otp !== '9543' || newPass.length < 4) { showToast('Enter OTP 9543 and new password!', '#e11d48'); return; } state.masterPassword = newPass; savePersistentState(); document.getElementById('master-forgot-box').classList.add('hidden'); showToast('๐Ÿ”‘ Master Password Updated!', '#10b981'); } function handleMasterLogin() { const email = document.getElementById('master-login-email').value.trim(); const pass = document.getElementById('master-login-pass').value.trim(); if (!email || (pass !== state.masterPassword && pass !== 'master123')) { showToast('Invalid Master Email or Password!', '#e11d48'); return; } state.masterAdminEmail = email; state.masterLoggedIn = true; renderMaster(); } function handleMasterLogout() { state.masterLoggedIn = false; renderMaster(); } function toggleMasterDrawer(forceState) { const sb = document.getElementById('master-sidebar'); const bd = document.getElementById('master-drawer-backdrop'); if (!sb) return; if (window.innerWidth <= 1280) { const nextOpen = typeof forceState === 'boolean' ? forceState : !sb.classList.contains('drawer-open'); sb.classList.toggle('drawer-open', nextOpen); if (bd) bd.classList.toggle('hidden', !nextOpen); } else { sb.classList.toggle('sidebar-collapsed'); } } function toggleMasterConnSubmenu() { document.getElementById('master-conn-submenu')?.classList.toggle('hidden'); } function switchMasterMenu(menu, apiFocus = 'all', closeDrawer = true) { state.masterMenu = menu; ['companies', 'add', 'connectivity', 'renewals', 'tickets', 'audit', 'cloud'].forEach(m => { document.getElementById('master-panel-' + m)?.classList.toggle('hidden', m !== menu); }); document.querySelectorAll('.v-sb-btn[data-mastermenu]').forEach(btn => btn.classList.toggle('active', btn.dataset.mastermenu === menu)); if (closeDrawer && window.innerWidth <= 1280) toggleMasterDrawer(false); renderMaster(); } function autoPreviewMasterRegId(nameVal) { const clean = nameVal.replace(/[^A-Za-z0-9]/g, '').toUpperCase(); const regInp = document.getElementById('master-new-regid'); if (regInp) regInp.value = clean ? `${clean.slice(0, 4)}-2026` : ''; previewMasterNewLicenseKey(); } function generateMasterNewRegId() { const rand = Math.floor(100 + Math.random() * 900); document.getElementById('master-new-regid').value = `CMP${rand}-2026`; } function previewMasterNewLicenseKey() { const nameVal = (document.getElementById('master-new-name')?.value || '').trim(); const regId = (document.getElementById('master-new-regid')?.value || '').trim().toUpperCase(); const months = Math.max(1, Number(document.getElementById('master-new-months')?.value) || 12); const serInp = document.getElementById('master-new-serial'); if (!serInp) return; if (!nameVal && !regId) { serInp.value = ''; return; } const baseCode = (regId || nameVal).replace(/[^A-Za-z0-9]/g, '').slice(0, 4).toUpperCase(); let hash = 0; for (let i = 0; i < (nameVal + regId).length; i++) hash = ((hash << 5) - hash) + (nameVal + regId).charCodeAt(i); const code4 = String(1000 + (Math.abs(hash) % 9000)); serInp.value = `AMBI-${baseCode}-${code4}-${months}M`; } function checkWhiteLabelDomainLink(rawDomain, regId) { const domain = (rawDomain || '').trim().toLowerCase().replace(/^https?:\/\//, '').split('/')[0]; if (!domain || !domain.includes('.')) { showToast('Enter valid subdomain (e.g. hr.ajsl.com)', '#e11d48'); return; } const box = document.getElementById('master-new-domain-status') || document.getElementById('master-edit-domain-status'); if (box) { box.classList.remove('hidden'); box.innerHTML = `โœ… Domain ${escapeHtmlSafe(domain)} verified for CNAME โ†’ app.ambicomputers.com (Tenant: ${escapeHtmlSafe(regId || 'NEW')})`; } showToast(`โœ… Domain ${domain} CNAME Ready!`, '#10b981'); } function toggleNewCompanyModule(modKey, checked) { state.newCompanyModules[modKey] = checked; } function handleMasterLogoUpload(event, targetMode) { const file = event.target.files?.[0]; if (!file) return; const reader = new FileReader(); reader.onload = e => { const dataUrl = e.target.result; if (targetMode === 'NEW') { state.tempNewCompanyLogo = dataUrl; const wrap = document.getElementById('master-new-logo-preview-wrap'); const img = document.getElementById('master-new-logo-preview'); if (wrap && img) { img.src = dataUrl; wrap.classList.remove('hidden'); } } else { state.tempEditCompanyLogo = dataUrl; const img = document.getElementById('master-edit-logo-preview'); const st = document.getElementById('master-edit-logo-status'); if (img) { img.src = dataUrl; img.classList.remove('hidden'); } if (st) st.textContent = 'โœ… New Logo Selected'; } showToast('๐Ÿ–ผ๏ธ Company Logo Uploaded!', '#10b981'); }; reader.readAsDataURL(file); } function toggleTenantModuleDirect(regId, modKey, checked) { const comp = state.registeredCompanies.find(c => c.regId === regId); if (comp) { comp.modules[modKey] = checked; savePersistentState(); renderAll(); } } function addCompanyFromMaster() { const name = document.getElementById('master-new-name').value.trim(); const regId = document.getElementById('master-new-regid').value.trim().toUpperCase(); const email = document.getElementById('master-new-email').value.trim() || 'admin@company.com'; const password = document.getElementById('master-new-pass').value.trim() || 'admin123'; const months = Math.max(1, Number(document.getElementById('master-new-months').value) || 12); const serial = document.getElementById('master-new-serial').value.trim() || buildSerialKeyForTenant(regId, months); if (!name || !regId) { showToast('Enter Client Company Name & Reg ID!', '#e11d48'); return; } state.registeredCompanies.unshift({ regId, name: name.toUpperCase(), gst: document.getElementById('master-new-gst').value.trim().toUpperCase(), phone: document.getElementById('master-new-phone').value.trim(), email, password, customDomain: (document.getElementById('master-new-domain')?.value || '').trim().toLowerCase(), address: document.getElementById('master-new-addr').value.trim() || 'Chennai, Tamil Nadu', logoInitials: name.slice(0, 2).toUpperCase(), logoUrl: state.tempNewCompanyLogo || '', licenseSerial: serial, licenseMonths: months, licenseStart: formatIsoDateOffset(0), licenseExpiry: formatIsoDateOffset(months * 30), licenseActivated: false, active: true, bikeKmRate: 4, carKmRate: 10, modules: { ...state.newCompanyModules }, commApis: { wa: false, sms: false, email: false } }); // Seed initial Trial Demo Data so the new company can explore before activating the License Key state.employees.push({ empId: `${regId.slice(0, 3)}-101`, companyRegId: regId, name: 'Demo Staff 1', role: 'Field Executive', deptId: 'BR_' + regId, shiftWindow: '09:30 AM - 06:30 PM', phone: '+91 98400 00001', aadhaar: '0000 0000 0001', pan: 'DEMOP1234A', bloodGroup: 'O+ve', address: 'Demo Trial Address', relationType: 'Family', emergencyName: 'Demo Contact', emergencyPhone: '+91 98400 00002', pin: '1234', status: 'OUT', rights: getDefaultStaffRights() }); state.punches.unshift({ id: 'P_DEMO_' + Date.now(), companyRegId: regId, date: '2026-11-27', empId: `${regId.slice(0, 3)}-101`, empName: 'Demo Staff 1', type: 'PUNCH IN', time: '09:30 AM', isLate: false, lat: 13.0827, lng: 80.2707, address: `${name.toUpperCase()} Demo Office`, selfieUrl: '', faceScore: '98.0%', voiceNote: false, remark: 'Trial Demo Punch (Will erase upon License Activation)' }); state.tempNewCompanyLogo = ''; const newLogoWrap = document.getElementById('master-new-logo-preview-wrap'); if (newLogoWrap) newLogoWrap.classList.add('hidden'); const newLogoInp = document.getElementById('master-new-logo-file'); if (newLogoInp) newLogoInp.value = ''; state.branches.push({ id: 'BR_' + regId, companyRegId: regId, name: `${name.toUpperCase()} Main Dept.`, shift: '09:30 AM - 06:30 PM', lead: 'Supervisor', lat: 13.0827, lng: 80.2707 }); copyTextToClipboard(serial); savePersistentState(); activateRegisteredCompany(regId, false); switchMasterMenu('companies', 'all', false); showToast(`โœ… Added "${name.toUpperCase()}" (Trial Mode) โ€ข Key ${serial} Copied!`, '#10b981'); } function clearDemoDataForFreshCompany(regId) { // Remove any preloaded demo/sample records so the newly created company starts 100% fresh state.employees = state.employees.filter(e => e.companyRegId !== regId); state.punches = state.punches.filter(p => p.companyRegId !== regId); state.trips = state.trips.filter(t => t.companyRegId !== regId); state.expenses = state.expenses.filter(ex => ex.companyRegId !== regId); state.leaves = state.leaves.filter(lv => lv.companyRegId !== regId); state.salaryAdvances = state.salaryAdvances.filter(ad => ad.companyRegId !== regId); state.tasks = state.tasks.filter(tk => tk.companyRegId !== regId); state.holidays = state.holidays.filter(hl => hl.companyRegId !== regId); state.supportTickets = state.supportTickets.filter(tk => tk.companyRegId !== regId); } function openEditMasterCompanyPanel(regId) { const comp = state.registeredCompanies.find(c => c.regId === regId); if (!comp) return; state.masterEditingRegId = regId; state.tempEditCompanyLogo = comp.logoUrl || ''; document.getElementById('master-edit-name').value = comp.name || ''; document.getElementById('master-edit-regid').value = comp.regId || ''; document.getElementById('master-edit-gst').value = comp.gst || ''; document.getElementById('master-edit-email').value = comp.email || ''; document.getElementById('master-edit-pass').value = comp.password || 'admin123'; document.getElementById('master-edit-domain').value = comp.customDomain || ''; document.getElementById('master-edit-serial').value = comp.licenseSerial || ''; document.getElementById('master-edit-expiry').value = comp.licenseExpiry || '2027-11-26'; document.getElementById('master-edit-phone').value = comp.phone || ''; document.getElementById('master-edit-addr').value = comp.address || ''; const prevImg = document.getElementById('master-edit-logo-preview'); const prevSt = document.getElementById('master-edit-logo-status'); if (prevImg && prevSt) { if (comp.logoUrl) { prevImg.src = comp.logoUrl; prevImg.classList.remove('hidden'); prevSt.textContent = 'Current Uploaded Logo'; } else { prevImg.classList.add('hidden'); prevSt.textContent = 'No logo uploaded yet'; } } document.getElementById('master-edit-company-box').classList.remove('hidden'); } function saveEditedMasterCompany() { const comp = state.registeredCompanies.find(c => c.regId === state.masterEditingRegId); if (!comp) return; comp.name = document.getElementById('master-edit-name').value.trim().toUpperCase(); comp.regId = document.getElementById('master-edit-regid').value.trim().toUpperCase(); comp.gst = document.getElementById('master-edit-gst').value.trim().toUpperCase(); comp.email = document.getElementById('master-edit-email').value.trim(); comp.password = document.getElementById('master-edit-pass').value.trim(); comp.customDomain = document.getElementById('master-edit-domain').value.trim().toLowerCase(); comp.licenseSerial = document.getElementById('master-edit-serial').value.trim().toUpperCase(); comp.licenseExpiry = document.getElementById('master-edit-expiry').value; comp.phone = document.getElementById('master-edit-phone').value.trim(); comp.address = document.getElementById('master-edit-addr').value.trim(); if (state.tempEditCompanyLogo) comp.logoUrl = state.tempEditCompanyLogo; document.getElementById('master-edit-company-box').classList.add('hidden'); savePersistentState(); activateRegisteredCompany(comp.regId, false); } function activateRegisteredCompany(regId, openCompanyConsole = false) { const found = state.registeredCompanies.find(c => c.regId === regId); if (!found) return; state.companyRegId = found.regId; state.companyName = found.name; state.companyGst = found.gst; state.companyPhone = found.phone; state.companyEmail = found.email; state.companyAddress = found.address; state.logoInitials = found.logoInitials || 'AJ'; state.companyLogoUrl = found.logoUrl || ''; state.bikeKmRate = found.bikeKmRate || 4; state.carKmRate = found.carKmRate || 10; const webEmailInp = document.getElementById('web-login-email'); const webPassInp = document.getElementById('web-login-pass'); if (webEmailInp && found.email) webEmailInp.value = found.email; if (webPassInp && found.password) webPassInp.value = found.password; if (openCompanyConsole) { state.webAdminEmail = found.email; state.webLoggedIn = true; setViewMode('company'); } else { renderAll(); } } function toggleClientCompanyActive(regId) { const comp = state.registeredCompanies.find(c => c.regId === regId); if (comp) { comp.active = !comp.active; savePersistentState(); renderAll(); } } function simulateExpireClientLicense(regId) { const comp = state.registeredCompanies.find(c => c.regId === regId); if (comp) { comp.licenseExpiry = formatIsoDateOffset(-2); savePersistentState(); renderAll(); } } function renewClientCompanyLicense(regId, customMonths) { const comp = state.registeredCompanies.find(c => c.regId === regId); if (!comp) return; const months = Math.max(1, Number(customMonths) || 12); const newKey = buildSerialKeyForTenant(regId, months); comp.licenseMonths = months; comp.licenseSerial = newKey; comp.licenseStart = formatIsoDateOffset(0); comp.licenseExpiry = formatIsoDateOffset(months * 30); comp.active = true; copyTextToClipboard(newKey); generateGstInvoiceForCompany(regId, months, newKey); savePersistentState(); renderAll(); } function renewSelectedClientLicense() { renewClientCompanyLicense(document.getElementById('master-renew-company-select')?.value, document.getElementById('master-renew-months-input')?.value); } function generateGstInvoiceForCompany(regId, months, serialKey) { const comp = state.registeredCompanies.find(c => c.regId === regId); if (!comp) return; const base = months * 450; const gstAmt = Math.round(base * 0.18); document.getElementById('master-gst-invoice-card').classList.remove('hidden'); document.getElementById('master-gst-invoice-body').innerHTML = `
Billed To: ${comp.name} โ€ข Key: ${serialKey} โ€ข Total: โ‚น${base + gstAmt}
`; } function selectMasterClientDetail(regId) { state.masterSelectedRegId = regId; activateRegisteredCompany(regId, false); } function createStaffFromMasterDetail() { const targetRegId = state.masterSelectedRegId || state.companyRegId; const empId = document.getElementById('master-staff-id').value.trim().toUpperCase(); const name = document.getElementById('master-staff-name').value.trim(); if (!empId || !name) return; state.employees.push({ empId, companyRegId: targetRegId, name, role: document.getElementById('master-staff-role').value.trim() || 'Field Staff', pin: document.getElementById('master-staff-pin').value.trim() || '1234', status: 'OUT', rights: getDefaultStaffRights() }); document.getElementById('master-staff-id').value = ''; document.getElementById('master-staff-name').value = ''; savePersistentState(); renderAll(); } function deleteStaffFromMaster(empId) { state.employees = state.employees.filter(e => e.empId !== empId); savePersistentState(); renderAll(); } function replyAndResolveMasterTicket(ticketId, markResolved = true) { const tkt = state.supportTickets.find(t => t.id === ticketId); if (tkt) { const inp = document.getElementById('master-reply-inp-' + ticketId); if (inp) tkt.masterReply = inp.value; if (markResolved) tkt.status = 'RESOLVED'; savePersistentState(); renderAll(); } } function reopenMasterTicket(ticketId) { const tkt = state.supportTickets.find(t => t.id === ticketId); if (tkt) { tkt.status = 'OPEN'; renderAll(); } } function saveMasterWhatsAppConfig() { state.whatsappApi.configured = true; savePersistentState(); renderMaster(); showToast('Saved CPaaSLink!', '#10b981'); } function testMasterWhatsAppConfig() { showToast('Sent Live Test WhatsApp!', '#10b981'); } function saveMasterSmsConfig() { state.smsApi.configured = true; renderMaster(); } function testMasterSmsConfig() { showToast('Sent Test SMS!', '#10b981'); } function saveMasterEmailGatewayConfig() { state.emailGatewayApi.configured = true; renderMaster(); } function testMasterEmailGatewayConfig() { showToast('Sent Test Email!', '#10b981'); } function sendAutoExpiryReminders() { showToast('Sent Expiry Reminders!', '#10b981'); } function pushMasterCloudSync() { savePersistentState(); showToast('โ˜๏ธ Synced with api.ambicomputers.com!', '#10b981'); } function pullMasterCloudSync() { loadPersistentState(); renderAll(); showToast('โฌ‡๏ธ Pulled Latest Data!', '#10b981'); } function renderMaster() { document.getElementById('master-login-screen').classList.toggle('hidden', state.masterLoggedIn); document.getElementById('master-dashboard-screen').classList.toggle('hidden', !state.masterLoggedIn); if (!state.masterLoggedIn) return; document.getElementById('master-kpi-companies').textContent = state.registeredCompanies.length; document.getElementById('master-sb-comp-badge').textContent = state.registeredCompanies.length; document.getElementById('master-kpi-staff').textContent = state.employees.length; document.getElementById('master-kpi-punches').textContent = state.punches.length; document.getElementById('master-kpi-active-comp').textContent = state.companyName; document.getElementById('master-kpi-active-regid').textContent = state.companyRegId; const newModGrid = document.getElementById('master-new-modules-grid'); if (newModGrid) { newModGrid.innerHTML = MODULE_DEFS.map(m => ``).join(''); } const q = (document.getElementById('master-search-input')?.value || '').trim().toLowerCase(); const filtered = state.registeredCompanies.filter(c => !q || c.name.toLowerCase().includes(q) || c.regId.toLowerCase().includes(q)); document.getElementById('master-table-count').textContent = filtered.length; const compTbody = document.getElementById('master-companies-tbody'); if (compTbody) { compTbody.innerHTML = filtered.map(c => { const daysLeft = computeRemainingDays(c.licenseExpiry); const logoThumb = c.logoUrl ? `Logo` : `${escapeHtmlSafe(c.logoInitials || 'CO')}`; return `
${logoThumb}
${escapeHtmlSafe(c.name)}
${escapeHtmlSafe(c.email)} โ€ข Pass: ${escapeHtmlSafe(c.password)}
${escapeHtmlSafe(c.regId)}
${escapeHtmlSafe(c.licenseSerial)}
${daysLeft}d left (${escapeHtmlSafe(c.licenseExpiry)})
${c.active ? 'โ— ACTIVE' : 'โ›” LOCKED'} `; }).join(''); } const selComp = state.registeredCompanies.find(c => c.regId === (state.masterSelectedRegId || state.companyRegId)) || state.registeredCompanies[0]; if (selComp) { const dName = document.getElementById('master-detail-name'); if (dName) dName.textContent = selComp.name; const dReg = document.getElementById('master-detail-regid'); if (dReg) dReg.textContent = selComp.regId; const dMeta = document.getElementById('master-detail-meta'); if (dMeta) dMeta.textContent = `Key: ${selComp.licenseSerial} โ€ข Expiry: ${selComp.licenseExpiry} โ€ข Admin: ${selComp.email}`; const dTarget = document.getElementById('master-detail-staff-target'); if (dTarget) dTarget.textContent = `${selComp.name} (${selComp.regId})`; const mods = selComp.modules || getAllModulesTrue(); const dModBox = document.getElementById('master-detail-modules-box'); if (dModBox) { dModBox.innerHTML = MODULE_DEFS.map(m => ``).join(''); } const detailStaff = state.employees.filter(e => (e.companyRegId || 'AJSL-2026') === selComp.regId); const dStaffBody = document.getElementById('master-detail-staff-tbody'); if (dStaffBody) { dStaffBody.innerHTML = detailStaff.map(e => `${e.empId}${e.name}${e.role} โ€ข PIN: ${e.pin}Active`).join(''); } } const renewSel = document.getElementById('master-renew-company-select'); if (renewSel) renewSel.innerHTML = state.registeredCompanies.map(c => ``).join(''); document.getElementById('master-renewals-tbody').innerHTML = state.registeredCompanies.map(c => ` ${c.name} ${c.licenseSerial} ${c.licenseExpiry} (${computeRemainingDays(c.licenseExpiry)}d) VALID `).join(''); document.getElementById('master-tickets-tbody').innerHTML = state.supportTickets.map(tk => ` ${tk.id} ${tk.companyName} ${tk.category} ${tk.subject} ${tk.status} `).join(''); document.getElementById('master-audit-tbody').innerHTML = state.auditLogs.map(log => `${log.time}${log.actor}${log.regId}${log.action}`).join(''); } function renderAll() { renderApk(); renderWeb(); renderMaster(); } function startClock() { const tick = () => { const now = new Date(); const el = document.getElementById('apk-clock'); if (el) el.textContent = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false }); const loginTimeEl = document.getElementById('apk-login-digital-time'); if (loginTimeEl) loginTimeEl.textContent = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true }); }; tick(); setInterval(tick, 1000); } window.addEventListener('online', () => { state.webDataSynced = true; updateWebSyncIndicator(); }); window.addEventListener('offline', () => { state.webDataSynced = false; updateWebSyncIndicator(); }); window.addEventListener('load', () => { loadPersistentState(); initApkSignPad(); startClock(); detectSubdomainRoute(); renderAll(); });