<!DOCTYPE html> <html lang="my"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <title>MiniTrend Kids — ကလေးပစ္စည်း အွန်လိုင်းဆိုင်</title> <meta name="theme-color" content="#ec4899" /> <meta name="mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-status-bar-style" content="default" /> <meta name="apple-mobile-web-app-title" content="MiniTrend Kids" /> <link id="app-manifest-link" rel="manifest" href="/manifest.json?v=16" /> <link rel="icon" type="image/png" href="./icon.png?v=3" /> <link rel="apple-touch-icon" href="./icon.png?v=3" /> <script> (function() { var isAdm = (new URLSearchParams(window.location.search).get('role') || '').toLowerCase() === 'admin'; if (isAdm) { var mf = document.getElementById('app-manifest-link'); if (mf) mf.setAttribute('href', './manifest-admin.json?v=1'); document.title = 'MiniTrend Admin — စီမံခန့်ခွဲမှု'; } })(); window.__deferredInstallPrompt = null; window.__currentFcmToken = ""; document.addEventListener('gesturestart', function(e) { e.preventDefault(); }); function isStandaloneApp() { return ( window.matchMedia('(display-mode: standalone)').matches || window.matchMedia('(display-mode: minimal-ui)').matches || window.matchMedia('(display-mode: fullscreen)').matches || window.navigator.standalone === true ); } function showInstallButtonsIfReady() { if (isStandaloneApp()) return; ['btn-install-app', 'btn-admin-install', 'btn-admin-install-login'].forEach(function(id) { var el = document.getElementById(id); if (el) el.classList.remove('hidden'); }); } window.addEventListener('beforeinstallprompt', function(e) { e.preventDefault(); window.__deferredInstallPrompt = e; showInstallButtonsIfReady(); }); window.addEventListener('appinstalled', function() { window.__deferredInstallPrompt = null; ['btn-install-app', 'btn-admin-install', 'btn-admin-install-login'].forEach(function(id) { var el = document.getElementById(id); if (el) el.classList.add('hidden'); }); }); </script> <script src="https://www.gstatic.com/firebasejs/10.13.2/firebase-app-compat.js"></script> <script src="https://www.gstatic.com/firebasejs/10.13.2/firebase-messaging-compat.js"></script> <script src="https://cdn.tailwindcss.com"></script> <style> html, body { touch-action: manipulation; -webkit-text-size-adjust: 100%; overflow-x: hidden; } body { font-family: 'Pyidaungsu', 'Myanmar Text', 'Noto Sans Myanmar', system-ui, -apple-system, sans-serif; padding-top: env(safe-area-inset-top, 0px); } .noti-safe-top { top: calc(0.75rem + env(safe-area-inset-top, 0px)); } button, a { touch-action: manipulation; } input, select, textarea { font-size: 16px !important; touch-action: manipulation; } .no-scrollbar::-webkit-scrollbar { display: none; } .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; } @keyframes slideDownNoti { 0% { transform: translate(-50%, -120%); opacity: 0; } 100% { transform: translate(-50%, 0); opacity: 1; } } .noti-slide-in { animation: slideDownNoti 0.35s cubic-bezier(0.16, 1, 0.3, 1) forwards; } @keyframes arrowNudgeRight { 0%, 100% { transform: translateX(0); } 50% { transform: translateX(5px); } } .gps-arrow-nudge { display: inline-block; animation: arrowNudgeRight 0.85s ease-in-out infinite; } </style> </head> <body class="bg-pink-50/35 text-gray-800 min-h-screen pb-16"> <script> const APPS_SCRIPT_URL = "https://script.google.com/macros/s/AKfycbzjiat7rNkOGkQYjf3RT6rC4g5AdXiVtraecqUTG8wXcu4l6Dm1mmtnXpVhaxjAzsrd/exec"; const ADMIN_PASS = "minitrend2026"; const DELIVERY_FEE_FLAT = 4500; const FIREBASE_CONFIG = { apiKey: "AIzaSyDyb--Qc9tic7g8GOzVWYi8vpLMSfTaI5U", authDomain: "minitrend-kids.firebaseapp.com", projectId: "minitrend-kids", storageBucket: "minitrend-kids.firebasestorage.app", messagingSenderId: "523213115439", appId: "1:523213115439:web:0e97b742e7d067943f36da" }; const FIREBASE_VAPID_KEY = "BEDkISmwDq6ytVzt2e-eWRndSXKxPttzdfxnKXETfJGhdnn_Se4b778DZ9YEi6NQDdy6gHuNz4twCZuKtzItqSI"; const CATEGORY_LIST = [ "အားလုံး", "🔥 Trending", "ဝမ်းဆက်", "နွေရာသီဝတ်", "အင်္ကျီ", "ဘောင်းဘီ", "ဦးထုတ်", "ဖိနပ်", "Baby Kits", "ဒိုင်ဘာ", "အနှီး", "လက်အိတ်၊ ခြေအိတ်", "ကုတင်၊ ပုခက်", "သင်ကြားရေး", "ကစားစရာ" ]; const AGE_REQUIRED_CATS = ["ဝမ်းဆက်", "နွေရာသီဝတ်", "အင်္ကျီ", "ဘောင်းဘီ", "ဦးထုတ်", "ဖိနပ်"]; const SIZE_LABELS = [ "၆ လ - ၁ နှစ်", "၁ နှစ် - ၂ နှစ်", "၂ - ၃ နှစ်", "၄ - ၅ နှစ်", "၆ - ၇ နှစ်", "၈ - ၉ နှစ်" ]; window.__swRegistrationPromise = null; if ('serviceWorker' in navigator) { window.__swRegistrationPromise = navigator.serviceWorker.register('/sw.js', { scope: '/' }).catch(() => null); } </script> <!-- TOP NOTIFICATION BANNER --> <div id="push-noti-popup" class="fixed noti-safe-top left-1/2 -translate-x-1/2 z-50 w-[94%] max-w-md hidden noti-slide-in"> <div class="bg-gray-900/95 text-white rounded-2xl p-3.5 shadow-2xl border-2 border-pink-400 flex items-start gap-3 backdrop-blur-md"> <img src="./icon.png?v=3" class="w-11 h-11 rounded-xl object-cover shrink-0 border border-white/20" /> <div class="flex-1 min-w-0"> <div class="flex justify-between items-center gap-1"> <p id="push-noti-title" class="text-xs sm:text-sm font-extrabold text-pink-300 truncate">🔔 MiniTrend Kids</p> <span class="text-[10px] text-gray-300 shrink-0">ယခုလေးတင်</span> </div> <p id="push-noti-body" class="text-xs sm:text-sm text-white font-bold mt-1 leading-relaxed"></p> </div> <button type="button" onclick="closePushPopup()" class="text-gray-400 hover:text-white font-bold text-lg leading-none px-1">✕</button> </div> </div> <!-- ===================================================================== --> <!-- 1. CUSTOMER STOREFRONT VIEW --> <!-- ===================================================================== --> <div id="customer-view" class="hidden"> <header class="sticky top-0 z-30 bg-white/95 backdrop-blur-md border-b border-pink-100 shadow-sm"> <div class="max-w-5xl mx-auto px-3.5 py-2.5 flex items-center justify-between gap-2"> <button type="button" onclick="goCustomerHome()" class="flex items-center gap-2 min-w-0 text-left"> <img src="./icon.png?v=3" alt="MiniTrend Kids" class="w-9 h-9 sm:w-10 sm:h-10 rounded-xl shadow-sm border border-pink-200 object-cover shrink-0"> <div class="min-w-0"> <h1 class="text-sm sm:text-lg font-extrabold text-pink-600 leading-tight truncate">MiniTrend Kids 🧸</h1> <p class="text-[10px] sm:text-xs text-gray-500 font-bold truncate">ပို့ခ ၄,၅၀၀ ကျပ် • ၃ ရက်အတွင်း</p> </div> </button> <div class="flex items-center gap-1.5 shrink-0"> <button type="button" id="btn-install-app" onclick="triggerCustomerInstall()" class="hidden bg-pink-50 hover:bg-pink-100 text-pink-700 border border-pink-200 text-[11px] font-extrabold px-2 py-2 rounded-xl">📲</button> <button type="button" onclick="openSizeCalcModal()" class="bg-purple-50 hover:bg-purple-100 text-purple-800 border border-purple-200 text-[11px] sm:text-xs font-extrabold px-2.5 py-2 rounded-xl flex items-center gap-1" title="ကလေး Size တိုင်းမည်"> 📏 <span>Size တိုင်း</span> </button> <button type="button" id="btn-cust-noti" onclick="enableCustomerNotifications()" class="bg-amber-50 hover:bg-amber-100 text-amber-800 border border-amber-200 text-xs font-extrabold px-2.5 py-2 rounded-xl" title="အသိပေးချက်ဖွင့်ရန်">🔔</button> <button type="button" onclick="openCartModal('cart')" class="relative bg-pink-600 hover:bg-pink-700 text-white text-xs sm:text-sm font-extrabold px-2.5 sm:px-3 py-2 rounded-xl shadow-sm flex items-center gap-1"> 🛍️ <span class="hidden sm:inline">ခြင်းတောင်း</span> <span id="cart-count-badge" class="bg-white text-pink-600 text-[11px] font-extrabold px-1.5 py-0.2 rounded-full">0</span> <span id="active-order-dot" class="hidden absolute -top-1 -right-1 w-3 h-3 bg-emerald-400 border-2 border-white rounded-full"></span> </button> </div> </div>
🛡️ ပစ္စည်းအစစ်အမှန် ၁၀၀% အာမခံသည် (အတုအပ လုံးဝမရောင်းပါ)
🔄 Size မှား၊ အရောင်မှား ဖြစ်ခဲ့လျှင် ၁၀၀% အခမဲ့ ပြန်လဲပေးသည်
⏳ ပစ္စည်းစာရင်းများ ရယူနေပါသည်...
</div> <!-- ================= KIDS SIZE CALCULATOR MODAL ================= --> <div id="size-calc-modal" onclick="closeSizeCalcModal()" class="fixed inset-0 bg-black/70 z-40 hidden flex items-end sm:items-center justify-center sm:p-4 backdrop-blur-sm"> <div onclick="event.stopPropagation()" class="bg-white rounded-t-3xl sm:rounded-3xl max-w-lg w-full max-h-[92vh] overflow-y-auto p-5 shadow-2xl border-2 border-purple-200 space-y-4"> <div class="flex justify-between items-center border-b pb-2.5 sticky top-0 bg-white z-10"> <h3 class="text-base font-extrabold text-purple-800">📏 ကလေး Size တိုင်းမည်</h3> <button type="button" onclick="closeSizeCalcModal()" class="text-gray-400 hover:text-gray-800 text-xl font-bold px-1">✕</button> </div>
</div> <!-- ================= PRODUCT DETAIL MODAL ================= --> <div id="product-modal" onclick="closeProductModal()" class="fixed inset-0 bg-black/70 z-40 hidden flex items-end sm:items-center justify-center sm:p-4 backdrop-blur-sm"> <div onclick="event.stopPropagation()" class="bg-white rounded-t-3xl sm:rounded-3xl max-w-lg w-full max-h-[92vh] overflow-y-auto shadow-2xl"> <div class="relative bg-gray-50"> <img id="pm-image" src="" alt="" class="w-full h-72 sm:h-80 object-contain bg-white"> <button type="button" onclick="closeProductModal()" class="absolute top-3 right-3 bg-black/60 hover:bg-black/80 text-white w-9 h-9 rounded-full flex items-center justify-center text-lg font-bold">✕</button> <span id="pm-sale-badge" class="hidden absolute top-3 left-3 bg-rose-600 text-white text-xs font-extrabold px-2.5 py-1 rounded-full shadow">SALE</span> </div> <div class="p-4 sm:p-5 space-y-3.5"> <div> <span id="pm-category" class="text-[11px] font-extrabold text-pink-600 bg-pink-50 px-2.5 py-0.5 rounded-full"></span> <h2 id="pm-name" class="text-base sm:text-lg font-extrabold text-gray-900 mt-1.5"></h2> <div class="flex items-baseline gap-2 mt-1"> <span id="pm-price" class="text-xl font-extrabold text-pink-600">0 ကျပ်</span> <span id="pm-orig-price" class="hidden text-xs text-gray-400 line-through font-bold"></span> </div> <p id="pm-desc" class="text-xs text-gray-600 mt-1.5 leading-relaxed whitespace-pre-line"></p> </div>

🎨 အရောင် / အမျိုးအစား ရွေးချယ်ပါ:

📏 အရွယ်အစား (Size) ရွေးချယ်ပါ:

1
</div> <!-- ================= CART & ORDER HISTORY MODAL ================= --> <div id="cart-modal" onclick="closeCartModal()" class="fixed inset-0 bg-black/70 z-40 hidden flex items-end sm:items-center justify-center sm:p-4 backdrop-blur-sm"> <div onclick="event.stopPropagation()" class="bg-white rounded-t-3xl sm:rounded-3xl max-w-lg w-full max-h-[92vh] overflow-y-auto shadow-2xl p-4 sm:p-5 space-y-4"> <div class="flex justify-between items-center border-b pb-3"> <h3 class="text-base font-extrabold text-gray-900">🛍️ ခြင်းတောင်းနှင့် အော်ဒါစစ်ဆေးရန်</h3> <button type="button" onclick="closeCartModal()" class="text-gray-400 hover:text-gray-800 text-xl font-bold px-1">✕</button> </div>
</div> <!-- ================= CUSTOMER ORDER HISTORY IMAGE LIGHTBOX ================= --> <div id="cust-order-img-lightbox" onclick="closeCustOrderImgLightbox()" class="fixed inset-0 bg-black/90 z-50 hidden flex flex-col items-center justify-center p-4 backdrop-blur-sm"> <button type="button" onclick="closeCustOrderImgLightbox()" class="fixed noti-safe-top right-3 z-50 bg-white/20 hover:bg-white/35 text-white w-10 h-10 rounded-full flex items-center justify-center text-xl font-bold shadow-lg">✕</button> <div onclick="event.stopPropagation()" class="max-w-md w-full flex flex-col items-center"> <img id="coil-img" src="" alt="" class="max-h-[65vh] w-auto max-w-full object-contain rounded-2xl shadow-2xl border border-white/15 bg-black/40"> <div class="mt-3 w-full bg-white rounded-2xl p-3.5 shadow-xl text-left"> <p id="coil-title" class="text-sm font-extrabold text-gray-900"></p> <p id="coil-meta" class="text-xs font-bold text-pink-600 mt-1"></p> </div> </div> </div> <!-- INSTALL GUIDE MODAL (CUSTOMER & ADMIN) --> <div id="ios-install-modal" onclick="closeIosInstallModal()" class="fixed inset-0 bg-black/75 z-50 hidden flex items-center justify-center p-4 backdrop-blur-sm"> <div onclick="event.stopPropagation()" class="bg-white rounded-2xl max-w-sm w-full p-5 shadow-2xl border-2 border-pink-300 space-y-3"> <div class="flex justify-between items-center border-b pb-2.5"> <h3 class="text-sm font-extrabold text-pink-600">📲 ဖုန်း Screen ပေါ် App ထည့်သွင်းနည်း</h3> <button type="button" onclick="closeIosInstallModal()" class="text-gray-400 font-bold text-xl px-1">✕</button> </div> <div class="space-y-2.5 text-xs text-gray-700 leading-relaxed"> <div class="bg-pink-50 border border-pink-200 rounded-xl p-3 space-y-1"> <p class="font-extrabold text-gray-900">🍎 iPhone (Safari ဖြင့်ဖွင့်ပါ):</p> <p>၁။ အောက်ခြေရှိ <b>Share (⬆️)</b> ခလုတ်ကို နှိပ်ပါ။</p> <p>၂။ <b>Add to Home Screen (➕)</b> ကို ရွေးပါ။</p> <p>၃။ ညာဘက်အပေါ်ရှိ <b>Add</b> ကို နှိပ်ပါ။</p> </div> <div class="bg-blue-50 border border-blue-200 rounded-xl p-3 space-y-1"> <p class="font-extrabold text-gray-900">🤖 Android (Chrome):</p> <p>အပေါ်ညာဘက် <b>⋮</b> နှိပ်ပြီး <b>Install app / Add to Home screen</b> ကို ရွေးပါ။</p> </div> </div> <button type="button" onclick="closeIosInstallModal()" class="w-full bg-gray-900 text-white font-extrabold py-2.5 rounded-xl text-xs">နားလည်ပါပြီ</button> </div> </div> <!-- ===================================================================== --> <!-- 2. ADMIN PANEL VIEW --> <!-- ===================================================================== --> <div id="admin-view" class="hidden max-w-6xl mx-auto px-3 sm:px-4 py-4">
🔐

Admin Panel ဝင်ရောက်ရန် v2.6

MiniTrend Kids ဆိုင်ပိုင်ရှင် စီမံခန့်ခွဲမှု

</div> <!-- ADMIN ITEM IMAGE PREVIEW LIGHTBOX --> <div id="admin-item-preview-modal" onclick="closeAdminItemPreview()" class="fixed inset-0 bg-black/90 z-50 hidden flex flex-col items-center justify-center p-4 backdrop-blur-sm"> <button type="button" onclick="closeAdminItemPreview()" class="fixed noti-safe-top right-3 z-50 bg-white/20 hover:bg-white/35 text-white w-10 h-10 rounded-full flex items-center justify-center text-xl font-bold">✕</button> <div onclick="event.stopPropagation()" class="max-w-md w-full flex flex-col items-center"> <img id="aip-img" src="" alt="" class="max-h-[65vh] w-auto max-w-full object-contain rounded-2xl shadow-2xl border border-white/15 bg-black/40"> <div class="mt-3 w-full bg-white rounded-2xl p-3.5 shadow-xl space-y-2"> <p id="aip-title" class="text-sm font-extrabold text-gray-900"></p> <p id="aip-meta" class="text-xs font-bold text-pink-600"></p> <button type="button" id="aip-download-btn" onclick="downloadFromPreviewModal(this)" class="hidden bg-blue-600 hover:bg-blue-700 text-white font-extrabold text-xs px-3.5 py-2 rounded-xl shadow-sm">⬇️ ပုံ Download ဆွဲမည်</button> </div> </div> </div> <!-- ADMIN RESTOCK FULL EDIT MODAL --> <div id="admin-restock-edit-modal" onclick="closeRestockEditModal()" class="fixed inset-0 bg-black/75 z-50 hidden flex items-end sm:items-center justify-center sm:p-4 backdrop-blur-sm"> <div onclick="event.stopPropagation()" class="bg-white rounded-t-3xl sm:rounded-3xl max-w-xl w-full max-h-[92vh] overflow-y-auto p-4 sm:p-5 shadow-2xl border-2 border-amber-300 space-y-3.5"> <div class="flex justify-between items-center border-b pb-2.5 sticky top-0 bg-white z-10"> <div> <h3 class="text-sm sm:text-base font-extrabold text-gray-900">✏️ Stock Request ပြင်ဆင်ရန် (Approve မလုပ်မီ)</h3> <p id="re-product-title" class="text-xs font-extrabold text-amber-700 mt-0.5"></p> </div> <button type="button" onclick="closeRestockEditModal()" class="text-gray-400 hover:text-gray-800 text-xl font-bold px-1">✕</button> </div>

📝 ပစ္စည်းအချက်အလက် ပြင်ဆင်ရန်

📷 ပစ္စည်းပုံများ ပြင်ဆင်ရန် (၁ မှ ၃ ပုံ)

0 / 3 ပုံ

</div> <!-- ADMIN REJECT RESTOCK REASON MODAL --> <div id="admin-reject-restock-modal" onclick="closeRejectRestockModal()" class="fixed inset-0 bg-black/75 z-50 hidden flex items-center justify-center p-4 backdrop-blur-sm"> <div onclick="event.stopPropagation()" class="bg-white rounded-2xl max-w-md w-full p-5 shadow-2xl border-2 border-red-300 space-y-3"> <div class="flex justify-between items-center border-b pb-2.5"> <h3 class="text-sm sm:text-base font-extrabold text-red-700">❌ Stock Request ပယ်ချရန်</h3> <button type="button" onclick="closeRejectRestockModal()" class="text-gray-400 hover:text-gray-800 text-xl font-bold px-1">✕</button> </div> <div id="rej-modal-info" class="bg-red-50 border border-red-200 rounded-xl p-2.5 text-xs font-bold text-gray-800"></div> <div class="space-y-1.5"> <p class="text-[11px] font-extrabold text-gray-600">⚡ အမြန်ရွေးရန် (သို့မဟုတ် အောက်တွင် ကိုယ်တိုင်ရေးပါ):</p> <div class="flex flex-wrap gap-1.5"> <button type="button" onclick="setQuickRejectReason('ပုံမကြည်လင်ပါ — ပုံအသစ်ပြန်ရိုက်ပို့ပေးပါ။')" class="bg-gray-100 hover:bg-red-50 text-gray-700 border border-gray-200 px-2.5 py-1 rounded-lg text-[11px] font-bold">📷 ပုံမကြည်လင်ပါ</button> <button type="button" onclick="setQuickRejectReason('ဈေးနှုန်း ပြန်လည်စစ်ဆေးပေးပါ။')" class="bg-gray-100 hover:bg-red-50 text-gray-700 border border-gray-200 px-2.5 py-1 rounded-lg text-[11px] font-bold">💰 ဈေးနှုန်းပြန်စစ်ပါ</button> <button type="button" onclick="setQuickRejectReason('ပစ္စည်းအချက်အလက် / Size မပြည့်စုံပါ။')" class="bg-gray-100 hover:bg-red-50 text-gray-700 border border-gray-200 px-2.5 py-1 rounded-lg text-[11px] font-bold">📝 အချက်အလက်မပြည့်စုံ</button> <button type="button" onclick="setQuickRejectReason('ပစ္စည်းအမည် သို့မဟုတ် အမျိုးအစား မှားယွင်းနေပါသည်။')" class="bg-gray-100 hover:bg-red-50 text-gray-700 border border-gray-200 px-2.5 py-1 rounded-lg text-[11px] font-bold">📂 အမျိုးအစားမှား</button> </div> </div> <div> <label class="block text-xs font-extrabold text-gray-700 mb-1">✍️ ပယ်ချရသည့် အကြောင်းပြချက် (ဆိုင် App တွင် ပေါ်ပါမည်)</label> <textarea id="rej-reason-input" rows="3" placeholder="ပယ်ချရသည့် အကြောင်းပြချက်ကို ရေးသားပါ..." class="w-full border-2 border-red-200 rounded-xl px-3 py-2 text-xs focus:outline-none focus:border-red-500"></textarea> <p id="rej-reason-err" class="hidden text-[11px] font-extrabold text-red-600 mt-1">⚠️ ပယ်ချရသည့် အကြောင်းပြချက် ရေးထည့်ပေးပါ။</p> </div> <div class="flex gap-2 pt-1"> <button type="button" onclick="closeRejectRestockModal()" class="flex-1 bg-gray-100 hover:bg-gray-200 text-gray-700 font-extrabold py-2.5 rounded-xl text-xs">မလုပ်တော့ပါ</button> <button type="button" id="btn-confirm-reject-restock" onclick="confirmAdminRejectRestock()" class="flex-1 bg-red-600 hover:bg-red-700 text-white font-extrabold py-2.5 rounded-xl text-xs shadow-sm">❌ ပယ်ချပြီး ဆိုင်ထံပို့မည်</button> </div> </div> </div> <!-- ADMIN WHITE ERASER BRUSH MODAL --> <div id="admin-photo-eraser-modal" class="fixed inset-0 bg-black/85 z-50 hidden flex items-center justify-center p-3 backdrop-blur-sm"> <div onclick="event.stopPropagation()" class="bg-white rounded-2xl max-w-lg w-full p-4 shadow-2xl border-2 border-emerald-300 space-y-3"> <div class="flex justify-between items-center border-b pb-2"> <div> <h3 class="text-sm font-extrabold text-gray-900">🖌️ အဖြူရောင်ခဲဖျက် (မလိုသောအရာ ဖျက်ရန်)</h3> <p class="text-[11px] text-gray-500 font-bold">မလိုချင်သော အစွန်းအစ သို့မဟုတ် ပစ္စည်းပေါ် လက်/မောက်စ်ဖြင့် ပွတ်ဖျက်ပါ</p> </div> <button type="button" onclick="closeWhiteEraserModal()" class="text-gray-400 hover:text-gray-800 text-xl font-bold px-1">✕</button> </div>
</div> <script> const urlParams = new URLSearchParams(window.location.search); const APP_ROLE = (urlParams.get('role') || 'customer').toLowerCase(); let allProducts = []; let selectedCategory = 'အားလုံး'; let modalProduct = null; let modalColorIdx = 0; let modalSizeIdx = 0; let modalQty = 1; let savedProductScrollY = null; let cart = []; let selectedSizeGender = 'boy'; let lastCalculatedSizeIdx = -1; let scSelectedCat = 'အားလုံး'; let customerActiveOrders = []; let serverTimeOffsetMs = 0; let adminDataCache = null; let currentAdminTab = 'orders'; let currentAdminOrderFilter = 'all'; let currentPayoutSubTab = 'unpaid'; let currentStockSubTab = 'own'; let currentNotiAudience = 'customer'; let currentCustNotiMode = 'all'; let pushPopupTimer = null; let activePreviewInfo = null; // Restock Full Editor & Reject Modal states let editingRestockId = ''; let editingRestockPhotos = []; let replacePhotoTargetIdx = -1; let rejectingRestockId = ''; const MAX_ADMIN_RESTOCK_PHOTOS = 3; // Admin OWN Product Manager states let ownMode = 'new'; let selectedOwnProduct = null; let ownPhotos = []; window.__adminPreviewMap = {}; window.__custOrderImgMap = {}; window.__b64ImgCache = {}; // ==================== MYANMAR LIVE CLOCK HELPER ==================== function getClientMyanmarTimeStr() { try { const nowMm = new Date(Date.now() + (6.5 * 60 * 60 * 1000)); const yr = nowMm.getUTCFullYear(); const mo = String(nowMm.getUTCMonth() + 1).padStart(2, '0'); const dy = String(nowMm.getUTCDate()).padStart(2, '0'); let hr = nowMm.getUTCHours(); const ampm = hr >= 12 ? 'PM' : 'AM'; hr = hr % 12 || 12; const mn = String(nowMm.getUTCMinutes()).padStart(2, '0'); const sc = String(nowMm.getUTCSeconds()).padStart(2, '0'); return `${yr}-${mo}-${dy} ${String(hr).padStart(2, '0')}:${mn}:${sc} ${ampm}`; } catch (e) { return ''; } } function updateAdminClock() { const el = document.getElementById('adm-mm-clock'); if (el) el.innerText = getClientMyanmarTimeStr(); } // ==================== BACK BUTTON NAVIGATION GUARD ==================== let isHandlingPopState = false; function pushAppOverlayState(overlayName) { if (isHandlingPopState) return; try { history.pushState({ mtOverlay: overlayName, ts: Date.now() }, ''); } catch (e) {} } function goCustomerHome() { const searchEl = document.getElementById('product-search'); if (searchEl) searchEl.value = ''; selectedCategory = 'အားလုံး'; renderCategoryBar(); renderProductsGrid(); window.scrollTo({ top: 0, behavior: 'smooth' }); } window.addEventListener('popstate', function() { if (APP_ROLE === 'admin') return; isHandlingPopState = true; try { const orderLightbox = document.getElementById('cust-order-img-lightbox'); if (orderLightbox && !orderLightbox.classList.contains('hidden')) { orderLightbox.classList.add('hidden'); return; } const sizeModal = document.getElementById('size-calc-modal'); if (sizeModal && !sizeModal.classList.contains('hidden')) { sizeModal.classList.add('hidden'); return; } const prodModal = document.getElementById('product-modal'); if (prodModal && !prodModal.classList.contains('hidden')) { closeProductModal(); return; } const cartModal = document.getElementById('cart-modal'); if (cartModal && !cartModal.classList.contains('hidden')) { cartModal.classList.add('hidden'); return; } const iosModal = document.getElementById('ios-install-modal'); if (iosModal && !iosModal.classList.contains('hidden')) { iosModal.classList.add('hidden'); return; } if (selectedCategory !== 'အားလုံး' || (document.getElementById('product-search')?.value || '').trim() !== '') { goCustomerHome(); } } finally { isHandlingPopState = false; } }); // ==================== HELPERS ==================== function escapeHtml(str) { return (str || '').toString() .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;') .replace(/"/g, '&quot;').replace(/'/g, '&#39;'); } function isIOSDevice() { const ua = navigator.userAgent || ''; return /iPad|iPhone|iPod/.test(ua) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1); } function normalizeShopId(v) { const s = (v || '').toString().trim().toUpperCase(); return s ? s : 'OWN'; } function mapLegacyCatClient(cat) { const c = (cat || '').trim(); if (c === 'မွေးကင်းစလေးများ' || c === 'မွေးကင်းစ') return 'Baby Kits'; return c; } function getProductSizeMode(categoryName) { const c = mapLegacyCatClient(categoryName); return AGE_REQUIRED_CATS.includes(c) ? 'standard' : 'none'; } function extractDriveIdClient(urlOrId) { if (!urlOrId) return ''; const s = urlOrId.toString().trim(); const m1 = s.match(/[?&]id=([a-zA-Z0-9_-]{15,})/); if (m1) return m1[1]; const m2 = s.match(/\/d\/([a-zA-Z0-9_-]{15,})/); if (m2) return m2[1]; if (/^[a-zA-Z0-9_-]{20,}$/.test(s)) return s; return ''; } function getSizedImageUrl(url, width = 400) { if (!url) return './icon.png?v=3'; const s = url.toString().trim(); if (!s || s.startsWith('data:') || s.startsWith('./') || s.startsWith('../')) return s; const fid = extractDriveIdClient(s); if (fid && (s.includes('drive.google.com') || s.includes('googleusercontent.com'))) { return `https://lh3.googleusercontent.com/d/${fid}=w${width}`; } return s; } async function loadDriveImageFallback(imgEl, fileId) { if (!imgEl || !fileId || imgEl.dataset.fallbackTried === '1') return; imgEl.dataset.fallbackTried = '1'; try { if (window.__b64ImgCache[fileId]) { imgEl.src = window.__b64ImgCache[fileId].dataUrl; return; } const res = await fetch(`${APPS_SCRIPT_URL}?action=getImageBase64&fileId=${encodeURIComponent(fileId)}&t=${Date.now()}`, { cache: 'no-store' }); const data = await res.json(); if (data && data.status === 'ok' && data.dataUrl) { window.__b64ImgCache[fileId] = data; imgEl.src = data.dataUrl; } } catch (e) {} } function dataUrlToBlob(dataUrl) { const parts = dataUrl.split(','); const mimeMatch = parts[0].match(/:(.*?);/); const mime = mimeMatch ? mimeMatch[1] : 'image/jpeg'; const raw = atob(parts[1]); const arr = new Uint8Array(raw.length); for (let i = 0; i < raw.length; i++) arr[i] = raw.charCodeAt(i); return new Blob([arr], { type: mime }); } async function downloadRestockImage(fileId, imageUrl, titleName, btnEl) { const origText = btnEl ? btnEl.innerText : ''; if (btnEl) { btnEl.disabled = true; btnEl.innerText = '⏳ ပုံဆွဲယူနေ...'; } const fid = fileId || extractDriveIdClient(imageUrl); const safeName = ((titleName || 'minitrend_product').replace(/[^a-zA-Z0-9\u1000-\u109F_-]+/g, '_').substring(0, 40) || 'product') + '.jpg'; try { if (imageUrl && imageUrl.startsWith('data:image/')) { const blob = dataUrlToBlob(imageUrl); const blobUrl = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = blobUrl; a.download = safeName; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => URL.revokeObjectURL(blobUrl), 4000); if (btnEl) { btnEl.disabled = false; btnEl.innerText = '✅ Download ပြီး'; setTimeout(() => { btnEl.innerText = origText || '⬇️ ပုံ Download ဆွဲမည်'; }, 2500); } return; } if (fid) { let imgData = window.__b64ImgCache[fid]; if (!imgData) { const res = await fetch(`${APPS_SCRIPT_URL}?action=getImageBase64&fileId=${encodeURIComponent(fid)}&t=${Date.now()}`, { cache: 'no-store' }); imgData = await res.json(); if (imgData && imgData.status === 'ok' && imgData.dataUrl) { window.__b64ImgCache[fid] = imgData; } } if (imgData && imgData.dataUrl) { const blob = dataUrlToBlob(imgData.dataUrl); const blobUrl = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = blobUrl; a.download = imgData.fileName || safeName; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => URL.revokeObjectURL(blobUrl), 4000); if (btnEl) { btnEl.disabled = false; btnEl.innerText = '✅ Download ပြီး'; setTimeout(() => { btnEl.innerText = origText || '⬇️ ပုံ Download ဆွဲမည်'; }, 2500); } return; } } if (imageUrl) { const resp = await fetch(imageUrl); const blob = await resp.blob(); const blobUrl = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = blobUrl; a.download = safeName; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => URL.revokeObjectURL(blobUrl), 4000); } } catch (e) { alert('⚠️ ပုံ Download ဆွဲရာတွင် အင်တာနက်ချိတ်ဆက်မှု စစ်ဆေးပြီး ထပ်စမ်းပေးပါ။'); } if (btnEl) { btnEl.disabled = false; btnEl.innerText = origText || '⬇️ ပုံ Download ဆွဲမည်'; } } function playNotiChime() { try { const AudioCtx = window.AudioContext || window.webkitAudioContext; if (!AudioCtx) return; const ctx = new AudioCtx(); const osc = ctx.createOscillator(); const gain = ctx.createGain(); osc.type = 'sine'; osc.frequency.setValueAtTime(880, ctx.currentTime); osc.frequency.setValueAtTime(1174.66, ctx.currentTime + 0.14); gain.gain.setValueAtTime(0.22, ctx.currentTime); gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.48); osc.connect(gain); gain.connect(ctx.destination); osc.start(); osc.stop(ctx.currentTime + 0.48); } catch (e) {} } function showBannerNoti(title, bodyText, tagId) { const dedupKey = 'mt_seen_noti_' + (tagId || (title + '|' + bodyText)); if (tagId && localStorage.getItem(dedupKey)) return; if (tagId) try { localStorage.setItem(dedupKey, '1'); } catch (e) {} const popup = document.getElementById('push-noti-popup'); document.getElementById('push-noti-title').innerText = "🔔 " + (title || "MiniTrend Kids"); document.getElementById('push-noti-body').innerText = bodyText || ""; popup.classList.remove('hidden'); playNotiChime(); if (navigator.vibrate) navigator.vibrate([200, 100, 200]); if (pushPopupTimer) clearTimeout(pushPopupTimer); pushPopupTimer = setTimeout(() => popup.classList.add('hidden'), 9000); } function closePushPopup() { document.getElementById('push-noti-popup').classList.add('hidden'); } function checkAndTriggerBroadcastNoti(latestNoti) { if (!latestNoti || !latestNoti.id || APP_ROLE === 'admin') return; const seenId = localStorage.getItem('mt_last_broadcast_id'); if (seenId === latestNoti.id) return; if (seenId) showBannerNoti(latestNoti.title, latestNoti.message, latestNoti.id); try { localStorage.setItem('mt_last_broadcast_id', latestNoti.id); } catch (e) {} } async function initFirebasePush(role, allowPrompt = false) { try { if (isIOSDevice() && !isStandaloneApp()) { return { ok: false, reason: 'ios_need_pwa', message: '🍎 iPhone တွင် Notification ရရန် Safari အောက်ခြေ Share (⬆️) → Add to Home Screen လုပ်ပြီး Home Screen icon မှ ဖွင့်ပေးပါ။' }; } if (!('Notification' in window) || !('serviceWorker' in navigator) || !('PushManager' in window)) { return { ok: false, reason: 'unsupported', message: '⚠️ ဤ Browser သည် Push Notification မပံ့ပိုးပါ။ Android ဆိုရင် Chrome ဖြင့်ဖွင့်ပါ။' }; } let perm = Notification.permission; if (perm === 'default' && allowPrompt) { perm = await Notification.requestPermission(); } if (perm === 'denied') { return { ok: false, reason: 'denied', message: '⚠️ Notification ကို Block ထားပါသည်။ Browser Settings → Notifications တွင် Allow ပြန်ဖွင့်ပေးပါ။' }; } if (perm !== 'granted') { return { ok: false, reason: 'not_granted', message: '⚠️ Notification popup ပေါ်လာလျှင် Allow ကို နှိပ်ပေးပါ။' }; } if (typeof firebase === 'undefined' || !firebase.messaging) { return { ok: false, reason: 'sdk_missing', message: '⚠️ Firebase SDK မဖတ်နိုင်သေးပါ။ Page ကို Refresh လုပ်ပြီး ထပ်နှိပ်ပါ။' }; } if (!firebase.apps.length) firebase.initializeApp(FIREBASE_CONFIG); const messaging = firebase.messaging(); if (!window.__fcmBound) { window.__fcmBound = true; messaging.onMessage((payload) => { const d = payload.data || {}; const n = payload.notification || {}; showBannerNoti(d.title || n.title || 'MiniTrend Kids', d.body || n.body || '', d.notiId || d.tag || ''); if (APP_ROLE === 'admin') loadAdminDashboard(true); else refreshCustomerOrders(false); }); } await navigator.serviceWorker.register('/sw.js', { scope: '/' }); const reg = await navigator.serviceWorker.ready; const token = await messaging.getToken({ vapidKey: FIREBASE_VAPID_KEY, serviceWorkerRegistration: reg }); if (!token) { return { ok: false, reason: 'no_token', message: '⚠️ FCM Token မထွက်ပါ။ အင်တာနက်စစ်ဆေးပြီး ထပ်စမ်းပါ။' }; } window.__currentFcmToken = token; let savedCust = null; try { savedCust = JSON.parse(localStorage.getItem('mt_cust_info') || 'null'); } catch (e) {} await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: 'saveFcmToken', token, role, phone: (role === 'customer' && savedCust) ? (savedCust.phone || '') : '', name: (role === 'customer' && savedCust) ? (savedCust.name || '') : '', device: (isIOSDevice() ? 'iOS PWA ' : '') + navigator.userAgent.substring(0, 70) }) }); if (role === 'admin') { const b = document.getElementById('btn-admin-fcm'); if (b) b.innerText = '✅ Noti ချိတ်ပြီး'; } else { const cb = document.getElementById('btn-cust-noti'); if (cb) cb.innerText = '🔔✓'; } return { ok: true, token }; } catch (e) { return { ok: false, reason: 'exception', message: '⚠️ Notification Error: ' + (e && e.message ? e.message : String(e)) }; } } // ==================== KIDS SIZE CALCULATOR + MATCHING PRODUCTS ==================== function openSizeCalcModal() { document.getElementById('size-calc-modal').classList.remove('hidden'); pushAppOverlayState('size_calc'); } function closeSizeCalcModal() { document.getElementById('size-calc-modal').classList.add('hidden'); } function selectSizeGender(g) { selectedSizeGender = g; const boyBtn = document.getElementById('sc-btn-boy'); const girlBtn = document.getElementById('sc-btn-girl'); if (g === 'boy') { boyBtn.className = 'border-2 border-blue-500 bg-blue-50 text-blue-800 font-extrabold py-2.5 rounded-xl text-xs'; girlBtn.className = 'border-2 border-gray-200 bg-white text-gray-700 font-bold py-2.5 rounded-xl text-xs'; } else { girlBtn.className = 'border-2 border-pink-500 bg-pink-50 text-pink-800 font-extrabold py-2.5 rounded-xl text-xs'; boyBtn.className = 'border-2 border-gray-200 bg-white text-gray-700 font-bold py-2.5 rounded-xl text-xs'; } } function calculateKidsSize() { const ageVal = parseFloat(document.getElementById('sc-age').value) || 1.5; const weightLb = parseFloat(document.getElementById('sc-weight').value) || 20; const genderText = selectedSizeGender === 'boy' ? 'သားသား' : 'မီးမီး'; let ageIdx = 0; if (ageVal <= 1) ageIdx = 0; else if (ageVal <= 2) ageIdx = 1; else if (ageVal <= 3.5) ageIdx = 2; else if (ageVal <= 5.5) ageIdx = 3; else if (ageVal <= 7.5) ageIdx = 4; else ageIdx = 5; let wtIdx = 0; if (weightLb <= 20) wtIdx = 0; else if (weightLb <= 26) wtIdx = 1; else if (weightLb <= 33) wtIdx = 2; else if (weightLb <= 44) wtIdx = 3; else if (weightLb <= 56) wtIdx = 4; else wtIdx = 5; const finalIdx = Math.min(5, Math.max(ageIdx, wtIdx)); const recSize = SIZE_LABELS[finalIdx]; lastCalculatedSizeIdx = finalIdx; scSelectedCat = 'အားလုံး'; document.getElementById('sc-result-size').innerText = recSize; document.getElementById('sc-result-note').innerText = wtIdx > ageIdx ? `${genderText}လေးက အလေးချိန် (${weightLb} ပေါင်) ပြည့်ဖြိုးလို့ ချောင်ချောင်ချိချိဝတ်ရအောင် "${recSize}" ကို ရွေးချယ်သင့်ပါတယ်ရှင် 💝` : `${genderText}လေး (${weightLb} ပေါင်) အတွက် "${recSize}" က အနေတော် အလှဆုံးဖြစ်ပါမယ်ရှင် 💝`; document.getElementById('sc-result-box').classList.remove('hidden'); renderSizeCalcMatchedProducts(finalIdx); } function filterSizeCalcCat(catName) { scSelectedCat = catName; if (lastCalculatedSizeIdx >= 0) renderSizeCalcMatchedProducts(lastCalculatedSizeIdx); } function renderSizeCalcMatchedProducts(sizeIdx) { const sec = document.getElementById('sc-products-section'); const countEl = document.getElementById('sc-products-count'); const pillsEl = document.getElementById('sc-cat-pills'); const gridEl = document.getElementById('sc-products-grid'); if (!sec || !gridEl) return; const allMatched = allProducts.filter(p => AGE_REQUIRED_CATS.includes(p.category) && (p.prices[sizeIdx] || 0) > 0 && (p.stocks[sizeIdx] || 0) > 0 ); sec.classList.remove('hidden'); if (countEl) countEl.innerText = `${allMatched.length} မျိုး`; if (allMatched.length === 0) { if (pillsEl) pillsEl.innerHTML = ''; gridEl.innerHTML = `<div class="col-span-2 bg-gray-50 border border-gray-200 rounded-xl p-5 text-center text-xs text-gray-500 font-bold">လက်ရှိ "${escapeHtml(SIZE_LABELS[sizeIdx])}" Size တွင် လက်ကျန်ရှိသော ပစ္စည်း မတွေ့ရှိသေးပါ။</div>`; return; } const availCats = ['အားလုံး', ...AGE_REQUIRED_CATS.filter(c => allMatched.some(p => p.category === c))]; if (pillsEl) { pillsEl.innerHTML = availCats.length > 2 ? availCats.map(c => { const active = c === scSelectedCat; return `<button type="button" onclick="filterSizeCalcCat('${escapeHtml(c)}')" class="${active ? 'bg-purple-600 text-white shadow-sm' : 'bg-purple-50 text-purple-800 hover:bg-purple-100'} px-2.5 py-1 rounded-full text-[11px] font-extrabold shrink-0 transition">${escapeHtml(c)}</button>`; }).join('') : ''; } const visibleList = scSelectedCat === 'အားလုံး' ? allMatched : allMatched.filter(p => p.category === scSelectedCat); gridEl.innerHTML = visibleList.map(p => { const imgUrl = getSizedImageUrl((p.colors[0] && p.colors[0].image) ? p.colors[0].image : './icon.png?v=3', 400); const exactPrice = p.prices[sizeIdx] || p.minPrice; return ` <div onclick="openProductFromSizeCalc(${p.id}, ${sizeIdx})" class="bg-white rounded-2xl border-2 border-purple-100 hover:border-pink-400 shadow-sm overflow-hidden cursor-pointer transition flex flex-col"> <div class="relative aspect-square bg-white"> <img src="${escapeHtml(imgUrl)}" loading="lazy" alt="${escapeHtml(p.name)}" class="w-full h-full object-contain p-1"> <span class="absolute top-1.5 left-1.5 bg-purple-600/90 text-white text-[9px] font-extrabold px-1.5 py-0.5 rounded-full">${escapeHtml(SIZE_LABELS[sizeIdx])}</span> <span class="absolute bottom-1.5 left-1.5 bg-emerald-600/90 text-white text-[9px] font-extrabold px-1.5 py-0.5 rounded-full">✅ မှာယူနိုင်ပါသည်</span> </div> <div class="p-2 flex-1 flex flex-col justify-between"> <div> <p class="text-[9px] font-bold text-pink-500">${escapeHtml(p.category)}</p> <p class="text-[11px] font-extrabold text-gray-900 line-clamp-2 leading-snug mt-0.5">${escapeHtml(p.name)}</p> </div> <div class="mt-1.5 flex items-center justify-between gap-1"> <span class="text-xs font-extrabold text-pink-600">${exactPrice.toLocaleString()} Ks</span> <span class="bg-pink-600 text-white text-[10px] font-extrabold px-2 py-0.5 rounded-lg">ရွေးမည်</span> </div> </div> </div> `; }).join(''); } function openProductFromSizeCalc(prodId, preselectedSizeIdx) { closeSizeCalcModal(); openProductModal(prodId, preselectedSizeIdx); } // ==================== LOAD & PARSE PRODUCTS ==================== function parseProductsRows(rows) { return (rows || []).map((r, idx) => { const prices = SIZE_LABELS.map((_, i) => parseInt(r[3 + i], 10) || 0); const stocks = SIZE_LABELS.map((_, i) => parseInt(r[19 + i], 10) || 0); const colors = []; if (r[9] || r[11]) colors.push({ name: r[9] || 'မူရင်း', image: getSizedImageUrl(r[11] || '', 1000) }); if (r[12] || r[13]) colors.push({ name: r[12] || 'အရောင် ၂', image: getSizedImageUrl(r[13] || '', 1000) }); if (r[14] || r[15]) colors.push({ name: r[14] || 'အရောင် ၃', image: getSizedImageUrl(r[15] || '', 1000) }); if (r[16] || r[17]) colors.push({ name: r[16] || 'အရောင် ၄', image: getSizedImageUrl(r[17] || '', 1000) }); if (colors.length === 0) colors.push({ name: 'မူရင်း', image: './icon.png?v=3' }); const validPrices = prices.filter(p => p > 0); const minPrice = validPrices.length > 0 ? Math.min(...validPrices) : 0; const totalStock = stocks.reduce((a, b) => a + b, 0); return { id: idx, name: (r[0] || '').trim(), category: mapLegacyCatClient(r[1] || ''), trending: (r[2] || '').toString().toUpperCase() === 'TRUE', prices, minPrice, colors, desc: [r[10], r[25]].filter(Boolean).join('\n'), origPrice: parseInt(r[18], 10) || 0, stocks, totalStock, shopId: normalizeShopId(r[26]) }; }).filter(p => p.name); } function loadProductsFromCacheInstant() { try { const cached = localStorage.getItem('mt_products_cache_v1'); if (!cached) return false; const parsed = JSON.parse(cached); if (Array.isArray(parsed) && parsed.length > 0) { allProducts = parseProductsRows(parsed); document.getElementById('products-loading')?.classList.add('hidden'); renderProductsGrid(); return true; } } catch (e) {} return false; } async function fetchJsonWithTimeout(url, timeoutMs = 9000) { const controller = typeof AbortController !== 'undefined' ? new AbortController() : null; const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null; try { const res = await fetch(url, { cache: 'no-store', signal: controller ? controller.signal : undefined }); if (timer) clearTimeout(timer); if (!res.ok) return null; return await res.json(); } catch (e) { if (timer) clearTimeout(timer); return null; } } async function loadProducts(forceRenderAdminStock = false) { let data = null; const useFresh = (APP_ROLE === 'admin' || forceRenderAdminStock); const proxyUrl = useFresh ? `/api/products?nocache=1&t=${Date.now()}` : `/api/products`; const proxyData = await fetchJsonWithTimeout(proxyUrl, 8000); if (proxyData && Array.isArray(proxyData.rows) && proxyData.rows.length > 0) { data = proxyData; } if (!data) { const directData = await fetchJsonWithTimeout(`${APPS_SCRIPT_URL}?action=getProducts&t=${Date.now()}`, 12000); if (directData && Array.isArray(directData.rows)) { data = directData; } } if (data && data.latestNoti) checkAndTriggerBroadcastNoti(data.latestNoti); if (data && Array.isArray(data.rows)) { try { localStorage.setItem('mt_products_cache_v1', JSON.stringify(data.rows)); } catch (e) {} allProducts = parseProductsRows(data.rows); } document.getElementById('products-loading')?.classList.add('hidden'); if (APP_ROLE !== 'admin') { renderProductsGrid(); if (lastCalculatedSizeIdx >= 0 && !document.getElementById('size-calc-modal').classList.contains('hidden')) { renderSizeCalcMatchedProducts(lastCalculatedSizeIdx); } } if (APP_ROLE === 'admin') { if (adminDataCache) renderAdminOrdersAndRiders(); if (forceRenderAdminStock || currentAdminTab === 'stock') { renderAdminStockPanel(); if (ownMode === 'existing') renderOwnExistingPicker(); } } } function lookupProductImage(prodName, colorName) { const p = allProducts.find(x => x.name === (prodName || '').trim()); if (!p) return ''; if (colorName) { const c = p.colors.find(col => col.name === colorName.trim()); if (c && c.image) return c.image; } return (p.colors[0] && p.colors[0].image) ? p.colors[0].image : ''; } // ==================== CUSTOMER STOREFRONT ==================== function renderCategoryBar() { const bar = document.getElementById('category-bar'); if (!bar) return; bar.innerHTML = CATEGORY_LIST.map(cat => { const active = cat === selectedCategory; return `<button type="button" onclick="selectCategory('${escapeHtml(cat)}')" class="${active ? 'bg-pink-600 text-white shadow-sm' : 'bg-pink-50 text-pink-800 hover:bg-pink-100'} px-3 py-1.5 rounded-full text-xs font-extrabold shrink-0 transition">${escapeHtml(cat)}</button>`; }).join(''); } function selectCategory(cat) { const wasHome = selectedCategory === 'အားလုံး'; selectedCategory = cat; renderCategoryBar(); renderProductsGrid(); if (wasHome && cat !== 'အားလုံး') pushAppOverlayState('cat_' + cat); } function renderProductsGrid() { const grid = document.getElementById('products-grid'); if (!grid) return; const q = (document.getElementById('product-search')?.value || '').trim().toLowerCase(); const filtered = allProducts.filter(p => { if (selectedCategory === '🔥 Trending' && !p.trending) return false; else if (selectedCategory !== 'အားလုံး' && selectedCategory !== '🔥 Trending' && p.category !== selectedCategory) return false; if (q && !p.name.toLowerCase().includes(q) && !p.category.toLowerCase().includes(q)) return false; return true; }); if (filtered.length === 0) { grid.innerHTML = `<div class="col-span-full text-center py-12 text-xs sm:text-sm text-gray-400">ရှာဖွေထားသော ပစ္စည်း မတွေ့ရှိပါ</div>`; return; } grid.innerHTML = filtered.map(p => { const isSoldOut = p.totalStock <= 0; const imgUrl = getSizedImageUrl((p.colors[0] && p.colors[0].image) ? p.colors[0].image : './icon.png?v=3', 400); const stockBadge = isSoldOut ? `<span class="bg-gray-800/85 text-white text-[10px] font-extrabold px-2 py-0.5 rounded-full">❌ ကုန်ပြီ</span>` : `<span class="bg-emerald-600/90 text-white text-[10px] font-extrabold px-2 py-0.5 rounded-full">✅ မှာယူနိုင်ပါသည်</span>`; return ` <div onclick="openProductModal(${p.id})" class="bg-white rounded-2xl shadow-sm border border-pink-100 overflow-hidden cursor-pointer hover:shadow-md transition flex flex-col"> <div class="relative aspect-square bg-white"> <img src="${escapeHtml(imgUrl)}" loading="lazy" alt="${escapeHtml(p.name)}" class="w-full h-full object-contain p-1 ${isSoldOut ? 'opacity-50 grayscale' : ''}"> ${p.trending ? `<span class="absolute top-2 left-2 bg-rose-500 text-white text-[10px] font-extrabold px-2 py-0.5 rounded-full shadow-sm">🔥 ခေတ်စား</span>` : ''} ${p.origPrice > p.minPrice ? `<span class="absolute top-2 right-2 bg-amber-400 text-gray-900 text-[10px] font-extrabold px-1.5 py-0.5 rounded-full">SALE</span>` : ''} <div class="absolute bottom-2 left-2">${stockBadge}</div> </div> <div class="p-2.5 flex-1 flex flex-col justify-between"> <div> <p class="text-[10px] font-bold text-pink-500">${escapeHtml(p.category)}</p> <h3 class="text-xs sm:text-sm font-extrabold text-gray-900 line-clamp-2 mt-0.5 leading-snug">${escapeHtml(p.name)}</h3> </div> <div class="mt-2 flex items-baseline gap-1.5 flex-wrap"> <span class="text-sm sm:text-base font-extrabold text-pink-600">${p.minPrice.toLocaleString()} Ks</span> ${p.origPrice > p.minPrice ? `<span class="text-[10px] text-gray-400 line-through">${p.origPrice.toLocaleString()}</span>` : ''} </div> </div> </div> `; }).join(''); } function openProductModal(prodId, forcedSizeIdx = -1) { const p = allProducts.find(x => x.id === prodId); if (!p) return; savedProductScrollY = window.scrollY || window.pageYOffset || 0; modalProduct = p; modalColorIdx = 0; modalQty = 1; const sizeMode = getProductSizeMode(p.category); if (sizeMode === 'standard') { if (forcedSizeIdx >= 0 && forcedSizeIdx < SIZE_LABELS.length && p.prices[forcedSizeIdx] > 0) { modalSizeIdx = forcedSizeIdx; } else { const firstAvail = SIZE_LABELS.findIndex((_, i) => p.prices[i] > 0 && p.stocks[i] > 0); const firstPriced = SIZE_LABELS.findIndex((_, i) => p.prices[i] > 0); modalSizeIdx = firstAvail !== -1 ? firstAvail : (firstPriced !== -1 ? firstPriced : 0); } } else { modalSizeIdx = 0; } renderProductModalState(); document.getElementById('product-modal').classList.remove('hidden'); pushAppOverlayState('product_modal'); } function closeProductModal() { document.getElementById('product-modal').classList.add('hidden'); if (typeof savedProductScrollY === 'number') { const targetY = savedProductScrollY; savedProductScrollY = null; if (Math.abs((window.scrollY || window.pageYOffset || 0) - targetY) > 10) { window.scrollTo(0, targetY); } } } function renderProductModalState() { if (!modalProduct) return; const p = modalProduct; const sizeMode = getProductSizeMode(p.category); const color = p.colors[modalColorIdx] || p.colors[0]; const price = p.prices[modalSizeIdx] || p.minPrice; const stk = sizeMode === 'none' ? p.totalStock : (p.stocks[modalSizeIdx] || 0); document.getElementById('pm-image').src = color.image || './icon.png?v=3'; document.getElementById('pm-category').innerText = p.category; document.getElementById('pm-name').innerText = p.name; document.getElementById('pm-price').innerText = price.toLocaleString() + ' ကျပ်'; document.getElementById('pm-desc').innerText = p.desc || ''; const origEl = document.getElementById('pm-orig-price'); const saleBadge = document.getElementById('pm-sale-badge'); if (p.origPrice > price) { origEl.innerText = p.origPrice.toLocaleString() + ' ကျပ်'; origEl.classList.remove('hidden'); saleBadge.classList.remove('hidden'); } else { origEl.classList.add('hidden'); saleBadge.classList.add('hidden'); } document.getElementById('pm-colors').innerHTML = p.colors.map((c, idx) => ` <button type="button" onclick="selectModalColor(${idx})" class="${idx === modalColorIdx ? 'border-pink-600 bg-pink-50 text-pink-700 ring-2 ring-pink-200' : 'border-gray-200 bg-white text-gray-700'} border-2 rounded-xl px-2.5 py-1.5 text-xs font-extrabold flex items-center gap-1.5"> ${c.image ? `<img src="${escapeHtml(c.image)}" class="w-6 h-6 rounded-md object-cover border">` : ''} <span>${escapeHtml(c.name)}</span> </button> `).join(''); const sizeSec = document.getElementById('pm-size-section'); const noSizeRow = document.getElementById('pm-no-size-stock-row'); const stkLabel = document.getElementById('pm-stock-label'); const noSizeStkLabel = document.getElementById('pm-no-size-stock-label'); if (sizeMode === 'none') { sizeSec.classList.add('hidden'); noSizeRow.classList.remove('hidden'); } else { sizeSec.classList.remove('hidden'); noSizeRow.classList.add('hidden'); document.getElementById('pm-sizes').innerHTML = SIZE_LABELS.map((sz, idx) => { if (p.prices[idx] <= 0) return ''; const sVal = p.stocks[idx] || 0; const active = idx === modalSizeIdx; return ` <button type="button" onclick="selectModalSize(${idx})" class="${active ? 'border-pink-600 bg-pink-50 text-pink-700' : 'border-gray-200 bg-white text-gray-700'} ${sVal <= 0 ? 'opacity-50 line-through' : ''} border-2 rounded-xl px-2 py-2 text-[11px] font-extrabold text-center"> <div>${escapeHtml(sz)}</div> <div class="text-[10px] font-bold text-gray-500 mt-0.5">${p.prices[idx].toLocaleString()} Ks</div> </button> `; }).join(''); } const addBtn = document.getElementById('btn-add-to-cart'); const activeStkEl = sizeMode === 'none' ? noSizeStkLabel : stkLabel; if (stk <= 0) { activeStkEl.innerText = '❌ ကုန်ပြီ'; activeStkEl.className = 'text-xs font-extrabold text-red-600'; addBtn.disabled = true; addBtn.innerText = '❌ ကုန်နေပါသည်'; addBtn.className = 'flex-1 bg-gray-300 text-gray-600 font-extrabold py-3 rounded-xl text-sm cursor-not-allowed'; } else { activeStkEl.innerText = '✅ မှာယူနိုင်ပါသည်'; activeStkEl.className = 'text-xs font-extrabold text-emerald-600'; addBtn.disabled = false; addBtn.innerText = '🛍️ ခြင်းတောင်းထဲ ထည့်မည်'; addBtn.className = 'flex-1 bg-pink-600 hover:bg-pink-700 text-white font-extrabold py-3 rounded-xl shadow text-sm'; } const sizeLabelCur = sizeMode === 'none' ? 'အသက်မလို' : SIZE_LABELS[modalSizeIdx]; const alreadyInCartCur = getCartQtyForProductSize(p.name, sizeLabelCur); const maxAllowed = Math.max(1, stk - alreadyInCartCur); if (modalQty > maxAllowed) modalQty = maxAllowed; document.getElementById('pm-qty').innerText = modalQty; } function getProductSizeStock(prodName, sizeLabel) { const p = allProducts.find(x => x.name === (prodName || '').trim()); if (!p) return 0; const sizeMode = getProductSizeMode(p.category); if (sizeMode === 'none' || !sizeLabel || sizeLabel === 'အသက်မလို') { return p.totalStock || 0; } const szIdx = SIZE_LABELS.indexOf(sizeLabel); return szIdx >= 0 ? (p.stocks[szIdx] || 0) : (p.totalStock || 0); } function getCartQtyForProductSize(prodName, sizeLabel) { const tName = (prodName || '').trim(); const tSize = (sizeLabel || 'အသက်မလို').trim(); return cart.reduce((sum, it) => { const itSize = (it.size || 'အသက်မလို').trim(); if (it.name === tName && itSize === tSize) return sum + Number(it.qty || 0); return sum; }, 0); } function selectModalColor(idx) { modalColorIdx = idx; renderProductModalState(); } function selectModalSize(idx) { modalSizeIdx = idx; modalQty = 1; renderProductModalState(); } function changeModalQty(delta) { if (!modalProduct) return; const sizeMode = getProductSizeMode(modalProduct.category); const sizeLabel = sizeMode === 'none' ? 'အသက်မလို' : SIZE_LABELS[modalSizeIdx]; const stk = sizeMode === 'none' ? modalProduct.totalStock : (modalProduct.stocks[modalSizeIdx] || 0); const alreadyInCart = getCartQtyForProductSize(modalProduct.name, sizeLabel); const remain = Math.max(0, stk - alreadyInCart); if (delta > 0 && modalQty >= remain) { showBannerNoti('⚠️ လက်ကျန်အရေအတွက် ပြည့်ပါပြီ', 'ဤပစ္စည်းအတွက် လက်ကျန်ရှိသလောက်သာ မှာယူနိုင်ပါသည်။'); return; } modalQty = Math.min(Math.max(1, remain), Math.max(1, modalQty + delta)); document.getElementById('pm-qty').innerText = modalQty; } // ==================== CART, AUTO-FILL & CHECKOUT ==================== function loadSavedCart() { try { cart = JSON.parse(localStorage.getItem('mt_cart') || '[]'); } catch (e) { cart = []; } updateCartBadge(); } function saveCart() { try { localStorage.setItem('mt_cart', JSON.stringify(cart)); } catch (e) {} updateCartBadge(); } function updateCartBadge() { const totalQty = cart.reduce((sum, i) => sum + Number(i.qty || 1), 0); const el = document.getElementById('cart-count-badge'); const cmEl = document.getElementById('cm-cart-num'); if (el) el.innerText = totalQty; if (cmEl) cmEl.innerText = totalQty; } function addCurrentProductToCart() { if (!modalProduct) return; const p = modalProduct; const sizeMode = getProductSizeMode(p.category); const color = p.colors[modalColorIdx] || p.colors[0]; const size = sizeMode === 'none' ? 'အသက်မလို' : SIZE_LABELS[modalSizeIdx]; const price = p.prices[modalSizeIdx] || p.minPrice; const stk = sizeMode === 'none' ? p.totalStock : (p.stocks[modalSizeIdx] || 0); if (stk <= 0) return; const alreadyInCart = getCartQtyForProductSize(p.name, size); const remain = Math.max(0, stk - alreadyInCart); if (remain <= 0) { showBannerNoti('⚠️ လက်ကျန်အရေအတွက် ပြည့်နေပါပြီ', 'ခြင်းတောင်းထဲတွင် ဤပစ္စည်းအတွက် လက်ကျန်ရှိသလောက် ထည့်ပြီးဖြစ်ပါသည်။'); return; } const qtyToAdd = Math.min(modalQty, remain); const existing = cart.find(i => i.name === p.name && i.colorName === color.name && i.size === size); if (existing) existing.qty += qtyToAdd; else cart.push({ name: p.name, colorName: color.name, size, qty: qtyToAdd, price, image: color.image || '', shopId: p.shopId }); saveCart(); closeProductModal(); showBannerNoti('🛍️ ခြင်းတောင်းထဲ ထည့်ပြီးပါပြီ', `${p.name} [${color.name}${size !== 'အသက်မလို' ? ' | ' + size : ''}] x ${qtyToAdd} ခု`); } function applyCustomerAutoFillFields(info) { if (!info) return; let filledAny = false; const setIfEmpty = (id, val) => { const el = document.getElementById(id); if (el && !el.value.trim() && val) { el.value = val; filledAny = true; } }; setIfEmpty('co-name', info.name); setIfEmpty('co-phone', info.phone); setIfEmpty('co-map-query', info.mapQuery); setIfEmpty('co-address-detail', info.addressDetail); setIfEmpty('co-map-location', info.mapLocation); setIfEmpty('track-phone-input', info.phone); if (filledAny) { document.getElementById('co-autofill-badge')?.classList.remove('hidden'); } } async function lookupCustomerAutoFillByPhone() { const ph = (document.getElementById('co-phone')?.value || '').trim(); const digits = ph.replace(/[^0-9]/g, ''); if (digits.length < 7) return; try { const res = await fetch(`${APPS_SCRIPT_URL}?action=getCustomerProfile&phone=${encodeURIComponent(ph)}&t=${Date.now()}`, { cache: 'no-store' }); const data = await res.json(); if (data && data.status === 'ok' && data.found && data.profile) { applyCustomerAutoFillFields(data.profile); try { localStorage.setItem('mt_cust_info', JSON.stringify({ name: data.profile.name || document.getElementById('co-name').value.trim(), phone: data.profile.phone || ph, mapQuery: data.profile.mapQuery || document.getElementById('co-map-query').value.trim(), addressDetail: data.profile.addressDetail || document.getElementById('co-address-detail').value.trim(), mapLocation: data.profile.mapLocation || document.getElementById('co-map-location').value.trim() })); } catch (e) {} } } catch (e) {} } function openCartModal(defaultTab = 'cart') { renderCartModal(); switchCartTab(defaultTab); try { const savedInfo = JSON.parse(localStorage.getItem('mt_cust_info') || 'null'); if (savedInfo) applyCustomerAutoFillFields(savedInfo); } catch (e) {} document.getElementById('cart-modal').classList.remove('hidden'); pushAppOverlayState('cart_modal'); if (defaultTab === 'orders') refreshCustomerOrders(false); } function closeCartModal() { document.getElementById('cart-modal').classList.add('hidden'); } function switchCartTab(tab) { document.getElementById('cm-panel-cart').classList.toggle('hidden', tab !== 'cart'); document.getElementById('cm-panel-orders').classList.toggle('hidden', tab !== 'orders'); document.getElementById('cm-tab-cart').className = tab === 'cart' ? 'py-2 rounded-lg text-xs font-extrabold bg-pink-600 text-white shadow-sm' : 'py-2 rounded-lg text-xs font-bold text-gray-700'; document.getElementById('cm-tab-orders').className = tab === 'orders' ? 'py-2 rounded-lg text-xs font-extrabold bg-pink-600 text-white shadow-sm' : 'py-2 rounded-lg text-xs font-bold text-gray-700'; } function renderCartModal() { const listEl = document.getElementById('cart-items-list'); const sumBox = document.getElementById('cart-summary-box'); if (cart.length === 0) { listEl.innerHTML = `<p class="text-xs text-gray-400 text-center py-8">🛍️ ခြင်းတောင်းထဲတွင် ပစ္စည်းမရှိသေးပါ</p>`; sumBox.classList.add('hidden'); return; } let sub = 0; listEl.innerHTML = cart.map((item, idx) => { const line = Number(item.price) * Number(item.qty); sub += line; const sizeLabelHtml = item.size && item.size !== 'အသက်မလို' ? ` | 📏 ${escapeHtml(item.size)}` : ''; return ` <div class="flex items-center gap-2.5 bg-gray-50 border border-pink-100 rounded-xl p-2.5"> <img src="${escapeHtml(item.image || './icon.png?v=3')}" class="w-14 h-14 rounded-xl object-cover border bg-white shrink-0"> <div class="flex-1 min-w-0"> <p class="font-extrabold text-xs text-gray-900 truncate">${escapeHtml(item.name)}</p> <p class="text-[11px] text-gray-600 font-bold">🎨 ${escapeHtml(item.colorName)}${sizeLabelHtml}</p> <p class="text-xs font-extrabold text-pink-600 mt-0.5">${line.toLocaleString()} Ks (${Number(item.price).toLocaleString()} x ${item.qty})</p> </div> <div class="flex flex-col items-end gap-1"> <button type="button" onclick="removeCartItem(${idx})" class="text-red-500 text-xs font-bold px-1.5">✕</button> <div class="flex items-center border rounded-lg bg-white text-xs font-extrabold"> <button type="button" onclick="updateCartItemQty(${idx}, -1)" class="px-2 py-0.5 text-pink-600">−</button> <span class="px-1.5">${item.qty}</span> <button type="button" onclick="updateCartItemQty(${idx}, 1)" class="px-2 py-0.5 text-pink-600">+</button> </div> </div> </div> `; }).join(''); document.getElementById('cart-subtotal').innerText = sub.toLocaleString() + ' ကျပ်'; document.getElementById('cart-grandtotal').innerText = (sub + DELIVERY_FEE_FLAT).toLocaleString() + ' ကျပ်'; sumBox.classList.remove('hidden'); } function removeCartItem(idx) { cart.splice(idx, 1); saveCart(); renderCartModal(); } function updateCartItemQty(idx, delta) { if (!cart[idx]) return; const item = cart[idx]; if (delta > 0) { const stk = getProductSizeStock(item.name, item.size); const totalInCart = getCartQtyForProductSize(item.name, item.size); if (totalInCart >= stk) { showBannerNoti('⚠️ လက်ကျန်အရေအတွက် ပြည့်ပါပြီ', `${item.name} အတွက် လက်ကျန်ရှိသလောက်သာ ထပ်တိုးနိုင်ပါသည်။`); return; } } item.qty = Math.max(1, item.qty + delta); saveCart(); renderCartModal(); } function captureCustomerGps() { const btn = document.getElementById('btn-get-gps'); const statusEl = document.getElementById('co-gps-status'); const inputEl = document.getElementById('co-map-location'); if (!navigator.geolocation) { statusEl.innerText = '⚠️ ဤဖုန်း Browser တွင် GPS မပံ့ပိုးပါ — Google Maps Link ထည့်နိုင်ပါသည်။'; statusEl.classList.remove('hidden'); return; } btn.disabled = true; btn.innerText = '⏳ ယူနေ...'; statusEl.innerText = '📡 GPS တည်နေရာ ရှာဖွေနေပါသည်...'; statusEl.classList.remove('hidden'); const onSuccess = (pos) => { const lat = pos.coords.latitude.toFixed(6); const lng = pos.coords.longitude.toFixed(6); inputEl.value = `${lat},${lng}`; statusEl.innerText = `✅ GPS တည်နေရာ ရရှိပြီးပါပြီ (${lat}, ${lng})`; btn.disabled = false; btn.innerText = '✅ ရရှိပြီး'; }; const onFallbackErr = () => { statusEl.innerText = '⚠️ ဖုန်း Location (GPS) ဖွင့်ထားကြောင်း စစ်ဆေးပါ (သို့မဟုတ် လိပ်စာအတိုင်း ဆက်တင်နိုင်သည်)။'; btn.disabled = false; btn.innerText = '📍 ထပ်ယူမည်'; }; navigator.geolocation.getCurrentPosition(onSuccess, () => { navigator.geolocation.getCurrentPosition(onSuccess, onFallbackErr, { enableHighAccuracy: false, timeout: 10000, maximumAge: 60000 }); }, { enableHighAccuracy: true, timeout: 8000, maximumAge: 0 }); } async function submitCustomerOrder(e) { e.preventDefault(); if (cart.length === 0) return; const name = document.getElementById('co-name').value.trim(); const phone = document.getElementById('co-phone').value.trim(); const mapQuery = document.getElementById('co-map-query').value.trim(); const addressDetail = document.getElementById('co-address-detail').value.trim(); const mapLocation = document.getElementById('co-map-location').value.trim(); const fullAddress = `${mapQuery} — ${addressDetail}`; const btn = document.getElementById('btn-submit-order'); btn.disabled = true; btn.innerText = '⏳ အော်ဒါတင်နေပါသည်...'; const orderId = 'MT-' + Math.floor(100000 + Math.random() * 900000); const subtotal = cart.reduce((s, i) => s + Number(i.price) * Number(i.qty), 0); const grandTotal = subtotal + DELIVERY_FEE_FLAT; const itemsText = cart.map((it, i) => { const szPart = it.size && it.size !== 'အသက်မလို' ? ` | အရွယ်: ${it.size}` : ''; return `${i + 1}. ${it.name} [အရောင်: ${it.colorName}${szPart}] x ${it.qty} ခု = ${(it.price * it.qty).toLocaleString()} Ks`; }).join('\n'); const orderedItemsPayload = cart.map(it => ({ name: it.name, colorName: it.colorName, size: it.size, qty: it.qty, price: it.price, image: it.image || lookupProductImage(it.name, it.colorName), shopId: normalizeShopId(it.shopId) })); try { localStorage.setItem('mt_cust_info', JSON.stringify({ name, phone, mapQuery, addressDetail, mapLocation })); const savedIds = JSON.parse(localStorage.getItem('mt_my_order_ids') || '[]'); savedIds.unshift(orderId); localStorage.setItem('mt_my_order_ids', JSON.stringify(savedIds.slice(0, 15))); } catch (err) {} try { await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ orderId, name, phone, address: fullAddress, mapQuery, addressDetail, mapLocation, itemsText, items: orderedItemsPayload, subtotal, delivery: DELIVERY_FEE_FLAT, grandTotal, fcmToken: window.__currentFcmToken || '' }) }); cart = []; saveCart(); renderCartModal(); switchCartTab('orders'); showBannerNoti(`✅ အော်ဒါတင်ပြီးပါပြီ! (${orderId})`, '၃ ရက်အတွင်း အိမ်အရောက် ပို့ဆောင်ပေးပါမည်ရှင် 💝'); setTimeout(() => { loadProducts(false); refreshCustomerOrders(false); }, 1200); } catch (err) { alert('⚠️ အော်ဒါတင်ရာတွင် အင်တာနက်ချိတ်ဆက်မှု စစ်ဆေးပေးပါ။'); } btn.disabled = false; btn.innerText = '✅ အော်ဒါတင်မည် (အိမ်ရောက်ငွေချေ)'; } // ==================== CUSTOMER ORDER HISTORY + 1-HOUR CANCEL ==================== function openCustOrderImgLightbox(key) { const info = window.__custOrderImgMap[key]; if (!info) return; document.getElementById('coil-img').src = info.image || './icon.png?v=3'; document.getElementById('coil-title').innerText = info.name || ''; const szPart = info.size && info.size !== 'အသက်မလို' ? ` | 📏 ${info.size}` : ''; document.getElementById('coil-meta').innerText = `🎨 ${info.colorName || '-'}${szPart} | 📦 x ${info.qty || 1} ခု`; document.getElementById('cust-order-img-lightbox').classList.remove('hidden'); pushAppOverlayState('order_img_lightbox'); } function closeCustOrderImgLightbox() { document.getElementById('cust-order-img-lightbox').classList.add('hidden'); } function formatRemainingCountdown(ms) { const totalSec = Math.max(0, Math.floor(ms / 1000)); const mins = Math.floor(totalSec / 60); const secs = totalSec % 60; const padSec = secs < 10 ? ('0' + secs) : secs; return `${mins} မိနစ် ${padSec} စက္ကန့်`; } function updateCancelCountdowns() { const btns = document.querySelectorAll('.cust-cancel-btn[data-deadline]'); if (!btns.length) return; const estServerNow = Date.now() + serverTimeOffsetMs; btns.forEach(btn => { const deadline = Number(btn.dataset.deadline || 0); const rem = deadline - estServerNow; if (rem <= 0) { const wrap = btn.closest('.cust-cancel-wrap'); if (wrap) wrap.remove(); else btn.remove(); } else { const lbl = btn.querySelector('.cancel-time-left'); if (lbl) lbl.innerText = formatRemainingCountdown(rem); } }); } async function customerCancelOrder(orderId, btnEl) { const reason = prompt(`အော်ဒါ #${orderId} ကို ပယ်ဖျက်လိုသည့် အကြောင်းရင်း (ရှိပါက ထည့်ရေးပါ — မထည့်လည်းရပါသည်):`, ''); if (reason === null) return; if (btnEl) { btnEl.disabled = true; btnEl.innerText = '⏳ ပေးပို့နေပါသည်...'; } const target = customerActiveOrders.find(x => x.orderId === orderId); if (target) { target.canCancel = false; target.cancelRequested = true; target.status = 'Cancel တောင်းဆိုထားသည်'; } try { await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: 'customerRequestCancel', orderId: orderId, reason: (reason || '').trim() || 'ဝယ်သူမှ ၁ နာရီအတွင်း Cancel တောင်းဆို' }) }); renderCustomerTrackingUI(); showBannerNoti(`⏳ Cancel တောင်းဆိုပြီးပါပြီ (${orderId})`, 'Admin မှ စစ်ဆေးပြီး ပယ်ဖျက်အတည်ပြုပေးပါမည်။'); setTimeout(() => refreshCustomerOrders(false), 1200); } catch (e) { alert('⚠️ အင်တာနက်ချိတ်ဆက်မှု စစ်ဆေးပြီး ပြန်စမ်းပေးပါ။'); } } async function refreshCustomerOrders(manual = false) { let savedIds = []; let phone = (document.getElementById('track-phone-input')?.value || '').trim(); try { savedIds = JSON.parse(localStorage.getItem('mt_my_order_ids') || '[]'); if (!phone) { const info = JSON.parse(localStorage.getItem('mt_cust_info') || 'null'); if (info && info.phone) phone = info.phone; } } catch (e) {} if (savedIds.length === 0 && phone.length < 7) return; try { const res = await fetch(`${APPS_SCRIPT_URL}?action=checkOrders&ids=${encodeURIComponent(savedIds.join(','))}&phone=${encodeURIComponent(phone)}&t=${Date.now()}`, { cache: 'no-store' }); const data = await res.json(); if (data && data.latestNoti) checkAndTriggerBroadcastNoti(data.latestNoti); if (data && data.status === 'ok') { if (data.serverNowMs) serverTimeOffsetMs = Number(data.serverNowMs) - Date.now(); customerActiveOrders = data.matchedOrders || []; renderCustomerTrackingUI(); } } catch (e) {} } function buildThreeStageProgressHtml(status, riderName) { if (status === 'ပယ်ဖျက်ပြီး') { return `<div class="bg-gray-200 text-gray-800 rounded-xl px-3 py-2 text-xs font-extrabold text-center">❌ ဤအော်ဒါကို ပယ်ဖျက်ပြီးပါပြီ</div>`; } if (status === 'Cancel တောင်းဆိုထားသည်') { return `<div class="bg-amber-100 border border-amber-300 text-amber-900 rounded-xl px-3 py-2 text-xs font-extrabold text-center">⏳ Cancel တောင်းဆိုထားပါသည် (Admin မှ စစ်ဆေးအတည်ပြုနေပါသည်)</div>`; } const step = status === 'ပို့ပြီး' ? 3 : (status === 'လာပို့နေပြီ' ? 2 : 1); const s1 = 'bg-emerald-600 text-white'; const s2 = step >= 2 ? 'bg-emerald-600 text-white' : 'bg-gray-200 text-gray-500'; const s3 = step >= 3 ? 'bg-emerald-600 text-white' : 'bg-gray-200 text-gray-500'; const l1 = step >= 2 ? 'bg-emerald-500' : 'bg-gray-200'; const l2 = step >= 3 ? 'bg-emerald-500' : 'bg-gray-200'; return ` <div class="pt-2"> <div class="flex items-center justify-between"> <div class="flex flex-col items-center w-20 text-center"> <span class="w-6 h-6 rounded-full ${s1} text-[11px] font-extrabold flex items-center justify-center">✓</span> <span class="text-[10px] font-extrabold text-emerald-700 mt-1 leading-tight">အော်ဒါလက်ခံပြီး</span> </div> <div class="flex-1 h-1 ${l1} rounded-full -mt-4"></div> <div class="flex flex-col items-center w-20 text-center"> <span class="w-6 h-6 rounded-full ${s2} text-[11px] font-extrabold flex items-center justify-center">${step >= 2 ? '🚚' : '2'}</span> <span class="text-[10px] font-extrabold ${step >= 2 ? 'text-emerald-700' : 'text-gray-400'} mt-1 leading-tight">လာပို့နေပြီ</span> </div> <div class="flex-1 h-1 ${l2} rounded-full -mt-4"></div> <div class="flex flex-col items-center w-20 text-center"> <span class="w-6 h-6 rounded-full ${s3} text-[11px] font-extrabold flex items-center justify-center">${step >= 3 ? '🎉' : '3'}</span> <span class="text-[10px] font-extrabold ${step >= 3 ? 'text-emerald-700' : 'text-gray-400'} mt-1 leading-tight">ပို့ပြီး</span> </div> </div> ${step === 2 && riderName ? `<p class="text-[11px] font-bold text-blue-700 bg-blue-50 border border-blue-200 rounded-lg px-2.5 py-1 mt-2 text-center">🚚 ပို့ဆောင်သူ: ${escapeHtml(riderName)} လာပို့နေပါပြီ</p>` : ''} </div> `; } function renderCustomerTrackingUI() { const dot = document.getElementById('active-order-dot'); const numEl = document.getElementById('cm-orders-num'); const bannerEl = document.getElementById('customer-tracking-banner'); const listEl = document.getElementById('customer-orders-list'); const activeOnly = customerActiveOrders.filter(o => o.status !== 'ပို့ပြီး' && o.status !== 'ပယ်ဖျက်ပြီး'); if (numEl) numEl.innerText = customerActiveOrders.length; if (dot) dot.classList.toggle('hidden', activeOnly.length === 0); if (activeOnly.length === 0) { bannerEl.classList.add('hidden'); } else { const topOrd = activeOnly[0]; bannerEl.classList.remove('hidden'); bannerEl.innerHTML = ` <div onclick="openCartModal('orders')" class="bg-white border-2 border-pink-200 rounded-2xl p-3 shadow-sm cursor-pointer"> <div class="flex justify-between items-center text-xs"> <span class="font-extrabold text-gray-900">📦 လက်ရှိအော်ဒါ: ${escapeHtml(topOrd.orderId)}</span> <span class="text-pink-600 font-extrabold">${Number(topOrd.grandTotal).toLocaleString()} Ks ▸</span> </div> ${buildThreeStageProgressHtml(topOrd.status, topOrd.riderName)} </div> `; } if (customerActiveOrders.length === 0) { listEl.innerHTML = `<p class="text-xs text-gray-400 text-center py-6">မှာထားသော အော်ဒါ မရှိသေးပါ။</p>`; return; } const estServerNow = Date.now() + serverTimeOffsetMs; window.__custOrderImgMap = {}; listEl.innerHTML = customerActiveOrders.map(o => { const itemsArr = Array.isArray(o.items) && o.items.length > 0 ? o.items : []; const itemsCardsHtml = itemsArr.length > 0 ? itemsArr.map((it, idx) => { const imgUrl = it.image || lookupProductImage(it.name, it.colorName) || './icon.png?v=3'; const key = `co_${o.orderId}_${idx}`; window.__custOrderImgMap[key] = { name: it.name, colorName: it.colorName, size: it.size, qty: it.qty, image: imgUrl }; const szHtml = it.size && it.size !== 'အသက်မလို' ? ` | 📏 ${escapeHtml(it.size)}` : ''; return ` <div class="flex items-center gap-2.5 bg-white border border-pink-100 rounded-xl p-2"> <button type="button" onclick="openCustOrderImgLightbox('${key}')" class="relative w-14 h-14 rounded-xl overflow-hidden border border-pink-200 shrink-0 bg-gray-50 cursor-zoom-in"> <img src="${escapeHtml(imgUrl)}" alt="" class="w-full h-full object-cover object-top"> <span class="absolute bottom-0.5 right-0.5 bg-black/65 text-white text-[8px] px-1 rounded">🔍</span> </button> <div class="flex-1 min-w-0 text-xs"> <p class="font-extrabold text-gray-900 truncate">${escapeHtml(it.name)}</p> <p class="text-[11px] font-bold text-gray-600">🎨 ${escapeHtml(it.colorName || '-')}${szHtml}</p> <p class="text-[11px] font-extrabold text-pink-600">x ${it.qty} ခု • ${(Number(it.price || 0) * Number(it.qty || 1)).toLocaleString()} Ks</p> </div> </div> `; }).join('') : `<p class="text-[11px] text-gray-700 whitespace-pre-line bg-white border rounded-xl p-2">${escapeHtml(o.itemsText)}</p>`; const remainMs = o.cancelDeadlineMs ? (Number(o.cancelDeadlineMs) - estServerNow) : 0; const showCancelBtn = !!o.canCancel && remainMs > 0; const cancelBtnHtml = showCancelBtn ? `<div class="cust-cancel-wrap pt-1"> <button type="button" data-deadline="${Number(o.cancelDeadlineMs)}" onclick="customerCancelOrder('${escapeHtml(o.orderId)}', this)" class="cust-cancel-btn w-full bg-red-50 hover:bg-red-100 text-red-700 border-2 border-red-200 font-extrabold py-2.5 px-3 rounded-xl text-xs transition"> ❌ ၁ နာရီအတွင်း Cancel တောင်းဆိုမည် (<span class="cancel-time-left">${formatRemainingCountdown(remainMs)}</span>) </button> </div>` : ''; const cardBorder = o.status === 'ပို့ပြီး' ? 'border-emerald-200' : (o.status === 'ပယ်ဖျက်ပြီး' ? 'border-gray-300 opacity-80' : 'border-pink-100'); return ` <div class="bg-gray-50 border-2 ${cardBorder} rounded-2xl p-3.5 space-y-2.5"> <div class="flex justify-between items-center text-xs"> <span class="font-extrabold text-gray-900">🧾 ${escapeHtml(o.orderId)}</span> <span class="text-[11px] text-gray-500">⏰ ${escapeHtml(o.dateTime)}</span> </div> ${buildThreeStageProgressHtml(o.status, o.riderName)} <div class="space-y-1.5">${itemsCardsHtml}</div> <p class="text-xs font-extrabold text-emerald-700 text-right">💰 စုစုပေါင်း (COD): ${Number(o.grandTotal).toLocaleString()} ကျပ်</p> ${cancelBtnHtml} </div> `; }).join(''); } async function triggerCustomerInstall() { if (window.__deferredInstallPrompt) { try { window.__deferredInstallPrompt.prompt(); await window.__deferredInstallPrompt.userChoice; window.__deferredInstallPrompt = null; } catch (e) {} return; } document.getElementById('ios-install-modal').classList.remove('hidden'); pushAppOverlayState('install_modal'); } function closeIosInstallModal() { document.getElementById('ios-install-modal').classList.add('hidden'); } async function enableCustomerNotifications() { const res = await initFirebasePush('customer', true); if (res && res.ok) alert('✅ အသိပေးချက် (Notification) ဖွင့်ပြီးပါပြီ!'); else alert((res && res.message) || '⚠️ Notification ဖွင့်မရပါ။'); } // ========================================================================= // ADMIN PANEL LOGIC // ========================================================================= function handleAdminLogin(e) { e.preventDefault(); const val = document.getElementById('admin-pass-input').value.trim(); if (val === ADMIN_PASS) { localStorage.setItem('mt_admin_authed', '1'); document.getElementById('admin-login-err').classList.add('hidden'); showAdminDashboard(); } else { document.getElementById('admin-login-err').classList.remove('hidden'); } } function logoutAdmin() { localStorage.removeItem('mt_admin_authed'); document.getElementById('admin-dashboard').classList.add('hidden'); document.getElementById('admin-login-box').classList.remove('hidden'); } function showAdminDashboard() { document.getElementById('admin-login-box').classList.add('hidden'); document.getElementById('admin-dashboard').classList.remove('hidden'); if (!isStandaloneApp()) { document.getElementById('btn-admin-install')?.classList.remove('hidden'); } initOwnProductManager(); updateAdminClock(); loadAdminDashboard(false); loadProducts(false); if ('Notification' in window && Notification.permission === 'granted') initFirebasePush('admin', false); } async function connectAdminFirebase() { const res = await initFirebasePush('admin', true); if (res && res.ok) alert('✅ Admin ဖုန်းကို Notification ချိတ်ဆက်ပြီးပါပြီ!'); else alert((res && res.message) || '⚠️ Admin Notification ချိတ်မရပါ။'); } function switchAdminTab(tab) { currentAdminTab = tab; ['orders', 'restocks', 'returns', 'payouts', 'stock', 'shops', 'riders', 'noti'].forEach(t => { const panel = document.getElementById('adm-panel-' + t); if (panel) panel.classList.toggle('hidden', t !== tab); const btn = document.getElementById('adm-tab-' + t); if (btn) { btn.className = t === tab ? 'px-3 py-2 rounded-xl text-xs font-extrabold bg-pink-600 text-white shrink-0' : 'px-3 py-2 rounded-xl text-xs font-bold text-gray-700 hover:bg-gray-100 shrink-0'; } }); if (tab === 'stock') { switchStockSubTab(currentStockSubTab); } if (tab === 'payouts' && currentPayoutSubTab === 'history') renderAdminPayoutHistory(); if (tab === 'noti') { renderCustomerNotiDropdown(); renderAdminCustomersList(); } } function switchStockSubTab(sub) { currentStockSubTab = sub; document.getElementById('adm-own-manager-wrap')?.classList.toggle('hidden', sub !== 'own'); document.getElementById('adm-stock-list-wrap')?.classList.toggle('hidden', sub !== 'list'); const btnOwn = document.getElementById('stk-sub-own'); const btnList = document.getElementById('stk-sub-list'); if (btnOwn && btnList) { if (sub === 'own') { btnOwn.className = 'py-2.5 px-3 rounded-xl text-xs font-extrabold bg-pink-600 text-white shadow-sm transition'; btnList.className = 'py-2.5 px-3 rounded-xl text-xs font-bold text-gray-700 hover:bg-gray-100 transition'; if (ownMode === 'existing') renderOwnExistingPicker(); } else { btnList.className = 'py-2.5 px-3 rounded-xl text-xs font-extrabold bg-emerald-600 text-white shadow-sm transition'; btnOwn.className = 'py-2.5 px-3 rounded-xl text-xs font-bold text-gray-700 hover:bg-gray-100 transition'; renderAdminStockPanel(); } } } function switchPayoutSubTab(sub) { currentPayoutSubTab = sub; document.getElementById('adm-payouts-unpaid-wrap').classList.toggle('hidden', sub !== 'unpaid'); document.getElementById('adm-payouts-history-wrap').classList.toggle('hidden', sub !== 'history'); const btnU = document.getElementById('pay-sub-unpaid'); const btnH = document.getElementById('pay-sub-history'); if (sub === 'unpaid') { btnU.className = 'py-2.5 px-3 rounded-xl text-xs font-extrabold bg-emerald-600 text-white shadow-sm transition'; btnH.className = 'py-2.5 px-3 rounded-xl text-xs font-bold text-gray-700 hover:bg-gray-100 transition'; } else { btnH.className = 'py-2.5 px-3 rounded-xl text-xs font-extrabold bg-blue-600 text-white shadow-sm transition'; btnU.className = 'py-2.5 px-3 rounded-xl text-xs font-bold text-gray-700 hover:bg-gray-100 transition'; renderAdminPayoutHistory(); } } function setAdminOrderFilter(f) { currentAdminOrderFilter = f; document.querySelectorAll('.adm-f-btn').forEach(btn => { if (btn.dataset.f === f) btn.className = 'adm-f-btn bg-gray-900 text-white px-3 py-1.5 rounded-full text-xs font-extrabold shrink-0'; else btn.className = 'adm-f-btn bg-white border border-gray-300 text-gray-700 px-3 py-1.5 rounded-full text-xs font-bold shrink-0'; }); renderAdminOrdersAndRiders(); } // ==================== SPLIT NOTI AUDIENCE (ALL / INDIVIDUAL CUSTOMERS) ==================== function switchCustNotiMode(mode) { currentCustNotiMode = mode; const btnAll = document.getElementById('noti-cust-mode-all'); const btnSingle = document.getElementById('noti-cust-mode-single'); const singleBox = document.getElementById('noti-cust-single-box'); const submitBtn = document.getElementById('btn-send-bc'); const hintEl = document.getElementById('noti-audience-hint'); if (mode === 'single') { btnSingle.className = 'py-2 px-2 rounded-lg text-xs font-extrabold bg-pink-600 text-white shadow-sm'; btnAll.className = 'py-2 px-2 rounded-lg text-xs font-bold bg-white text-pink-900 border border-pink-200'; singleBox.classList.remove('hidden'); renderCustomerNotiDropdown(); if (currentNotiAudience === 'customer') { hintEl.innerText = '👤 ရွေးချယ်ထားသော ဝယ်သူတစ်ဦးတည်းထံသို့သာ Notification ပေးပို့ပါမည်။'; submitBtn.innerText = '🚀 ရွေးထားသော ဝယ်သူထံ ပို့မည်'; } } else { btnAll.className = 'py-2 px-2 rounded-lg text-xs font-extrabold bg-pink-600 text-white shadow-sm'; btnSingle.className = 'py-2 px-2 rounded-lg text-xs font-bold bg-white text-pink-900 border border-pink-200'; singleBox.classList.add('hidden'); if (currentNotiAudience === 'customer') { hintEl.innerText = '🛍️ ဝယ်သူ App (Customer) တွင် Notification ဖွင့်ထားသူအားလုံးထံ ရောက်ရှိပါမည်။'; submitBtn.innerText = '🚀 ဝယ်သူအားလုံးထံ ပို့မည်'; } } } function renderCustomerNotiDropdown() { const sel = document.getElementById('bc-cust-target'); if (!sel) return; const list = (adminDataCache && Array.isArray(adminDataCache.customers)) ? adminDataCache.customers : []; const q = (document.getElementById('bc-cust-search')?.value || '').trim().toLowerCase(); const prevVal = sel.value; const filtered = list.filter(c => { if (!q) return true; return (c.name || '').toLowerCase().includes(q) || (c.phone || '').includes(q); }); sel.innerHTML = `<option value="">-- ဝယ်သူ ရွေးချယ်ပါ (${filtered.length} ဦး) --</option>` + filtered.map(c => `<option value="customer:${escapeHtml(c.phone)}">${c.hasFcmToken ? '🔔 ' : ''}${escapeHtml(c.name)} - ${escapeHtml(c.phone)}</option>`).join(''); if ([...sel.options].some(o => o.value === prevVal)) sel.value = prevVal; } function pickCustomerForNoti(phone) { switchNotiAudience('customer'); switchCustNotiMode('single'); const sel = document.getElementById('bc-cust-target'); if (sel) { sel.value = 'customer:' + phone; document.getElementById('bc-title')?.focus(); } } function renderAdminCustomersList() { const box = document.getElementById('adm-customers-list'); const cntEl = document.getElementById('adm-customers-count'); if (!box) return; const list = (adminDataCache && Array.isArray(adminDataCache.customers)) ? adminDataCache.customers : []; if (cntEl) cntEl.innerText = list.length; const q = (document.getElementById('adm-customers-search')?.value || '').trim().toLowerCase(); const filtered = list.filter(c => { if (!q) return true; return (c.name || '').toLowerCase().includes(q) || (c.phone || '').includes(q) || (c.address || '').toLowerCase().includes(q); }); if (filtered.length === 0) { box.innerHTML = `<p class="text-gray-400 py-4 text-center">ဝယ်သူစာရင်း မရှိသေးပါ။</p>`; return; } box.innerHTML = filtered.map(c => ` <div class="py-2 flex flex-wrap justify-between items-center gap-2"> <div class="min-w-0 flex-1"> <p class="font-extrabold text-gray-900 truncate"> 👤 ${escapeHtml(c.name)} - <a href="tel:${escapeHtml(c.phone)}" class="text-blue-700 underline">${escapeHtml(c.phone)}</a> ${c.hasFcmToken ? `<span class="bg-emerald-100 text-emerald-800 px-1.5 py-0.5 rounded text-[10px] ml-1">🔔 Noti</span>` : ''} </p> <p class="text-[11px] text-gray-500 truncate">📦 အော်ဒါ: <b>${c.orderCount || 0} ကြိမ်</b>${c.address ? ` • 📍 ${escapeHtml(c.address)}` : ''}</p> </div> <button type="button" onclick="pickCustomerForNoti('${escapeHtml(c.phone)}')" class="bg-pink-100 hover:bg-pink-200 text-pink-800 font-extrabold px-2.5 py-1 rounded-lg text-[11px] shrink-0">📩 Noti ပို့</button> </div> `).join(''); } function switchNotiAudience(aud) { currentNotiAudience = aud; const btnCust = document.getElementById('noti-aud-customer'); const btnRider = document.getElementById('noti-aud-rider'); const btnShop = document.getElementById('noti-aud-shop'); const custWrap = document.getElementById('noti-cust-select-wrap'); const riderWrap = document.getElementById('noti-rider-select-wrap'); const shopWrap = document.getElementById('noti-shop-select-wrap'); const hintEl = document.getElementById('noti-audience-hint'); const titleInput = document.getElementById('bc-title'); const submitBtn = document.getElementById('btn-send-bc'); const baseIdle = 'py-2.5 px-2 rounded-lg text-xs font-bold text-gray-700 hover:bg-white transition'; btnCust.className = aud === 'customer' ? 'py-2.5 px-2 rounded-lg text-xs font-extrabold bg-pink-600 text-white shadow-sm transition' : baseIdle; btnRider.className = aud === 'rider' ? 'py-2.5 px-2 rounded-lg text-xs font-extrabold bg-blue-600 text-white shadow-sm transition' : baseIdle; btnShop.className = aud === 'shop' ? 'py-2.5 px-2 rounded-lg text-xs font-extrabold bg-amber-600 text-white shadow-sm transition' : baseIdle; custWrap.classList.toggle('hidden', aud !== 'customer'); riderWrap.classList.toggle('hidden', aud !== 'rider'); shopWrap.classList.toggle('hidden', aud !== 'shop'); if (aud === 'customer') { hintEl.className = 'text-[11px] font-bold text-pink-700 bg-pink-50 border border-pink-200 rounded-xl px-3 py-2'; titleInput.placeholder = 'ခေါင်းစဉ် (ဥပမာ - 🎁 ပစ္စည်းအသစ်များ ရောက်ပါပြီ!)'; submitBtn.className = 'bg-pink-600 hover:bg-pink-700 text-white font-extrabold px-5 py-2.5 rounded-xl text-xs shadow-sm'; switchCustNotiMode(currentCustNotiMode); } else if (aud === 'rider') { hintEl.className = 'text-[11px] font-bold text-blue-800 bg-blue-50 border border-blue-200 rounded-xl px-3 py-2'; hintEl.innerText = '🚚 ရွေးချယ်ထားသော Delivery ဝန်ထမ်း App ထံသို့သာ ရောက်ရှိမည် (ဝယ်သူနှင့် ဆိုင်ဘက် မပေါ်ပါ)။'; titleInput.placeholder = 'ခေါင်းစဉ် (ဥပမာ - 🚚 ယနေ့ ပို့ဆောင်ရေး အရေးကြီးအသိပေးချက်)'; submitBtn.className = 'bg-blue-600 hover:bg-blue-700 text-white font-extrabold px-5 py-2.5 rounded-xl text-xs shadow-sm'; submitBtn.innerText = '🚀 Delivery ဝန်ထမ်းထံ ပို့မည်'; } else { hintEl.className = 'text-[11px] font-bold text-amber-900 bg-amber-50 border border-amber-200 rounded-xl px-3 py-2'; hintEl.innerText = '🏪 ရွေးချယ်ထားသော ချိတ်ဆက်ဆိုင် App ထံသို့သာ ရောက်ရှိမည် (ညနေ ၆:၀၀ မှ နံနက် ၈:၀၀ Auto Mute ချိန်တွင် မပို့ပါ)။'; titleInput.placeholder = 'ခေါင်းစဉ် (ဥပမာ - 🏪 ချိတ်ဆက်ဆိုင်များအတွက် အသိပေးချက်)'; submitBtn.className = 'bg-amber-600 hover:bg-amber-700 text-white font-extrabold px-5 py-2.5 rounded-xl text-xs shadow-sm'; submitBtn.innerText = '🚀 ဆိုင် App ထံ ပို့မည်'; } } // ==================== ADMIN OWN PRODUCT MANAGER (ADD / RESTOCK / AI BG) ==================== function initOwnProductManager() { const catSel = document.getElementById('own-category'); if (catSel && catSel.options.length === 0) { const catsOnly = CATEGORY_LIST.filter(c => c !== 'အားလုံး' && c !== '🔥 Trending'); catSel.innerHTML = catsOnly.map(c => `<option value="${escapeHtml(c)}">${escapeHtml(c)}</option>`).join(''); } updateOwnSizeOptions(); renderOwnPhotoSlots(); } function setOwnMode(mode) { ownMode = mode; const btnNew = document.getElementById('own-mode-new'); const btnEx = document.getElementById('own-mode-existing'); const picker = document.getElementById('own-existing-picker'); if (mode === 'existing') { btnEx.className = 'py-2 px-2 rounded-lg text-xs font-extrabold bg-blue-600 text-white shadow-sm transition'; btnNew.className = 'py-2 px-2 rounded-lg text-xs font-bold text-pink-900 hover:bg-pink-100 transition'; picker.classList.remove('hidden'); renderOwnExistingPicker(); } else { btnNew.className = 'py-2 px-2 rounded-lg text-xs font-extrabold bg-pink-600 text-white shadow-sm transition'; btnEx.className = 'py-2 px-2 rounded-lg text-xs font-bold text-pink-900 hover:bg-pink-100 transition'; picker.classList.add('hidden'); clearOwnSelection(true); } } function getOwnProductsList() { const fromAll = allProducts.filter(p => p.shopId === 'OWN'); if (fromAll.length > 0) return fromAll; return (adminDataCache && Array.isArray(adminDataCache.ownProducts)) ? adminDataCache.ownProducts : []; } function renderOwnExistingPicker() { const box = document.getElementById('own-existing-list'); const cntEl = document.getElementById('own-existing-count'); if (!box) return; const list = getOwnProductsList(); const q = (document.getElementById('own-existing-search')?.value || '').trim().toLowerCase(); if (cntEl) cntEl.innerText = `${list.length} မျိုး`; const filtered = list.filter(p => !q || (p.name || '').toLowerCase().includes(q) || (p.category || '').toLowerCase().includes(q)); if (filtered.length === 0) { box.innerHTML = `<p class="text-xs text-gray-500 text-center py-3 bg-white rounded-xl border">OWN ပစ္စည်း မတွေ့ရှိပါ</p>`; return; } box.innerHTML = filtered.map((p) => { const origIdx = list.indexOf(p); const imgUrl = getSizedImageUrl((p.colors && p.colors[0] && p.colors[0].image) ? p.colors[0].image : './icon.png?v=3', 200); const isSel = selectedOwnProduct && selectedOwnProduct.name === p.name; return ` <div onclick="selectOwnExistingProduct(${origIdx})" class="cursor-pointer flex items-center gap-2 p-2 rounded-xl border-2 ${isSel ? 'border-emerald-500 bg-emerald-50' : 'border-blue-100 bg-white hover:border-blue-400'}"> <img src="${escapeHtml(imgUrl)}" class="w-10 h-10 rounded-lg object-cover border shrink-0"> <div class="flex-1 min-w-0 text-xs"> <p class="font-extrabold text-gray-900 truncate">${escapeHtml(p.name)}</p> <p class="text-[10px] font-bold text-gray-600">📂 ${escapeHtml(p.category)} • 📦 လက်ကျန်: <span class="text-emerald-700">${p.totalStock || 0}</span></p> </div> <span class="bg-blue-600 text-white text-[10px] font-extrabold px-2 py-1 rounded-lg shrink-0">ရွေး</span> </div> `; }).join(''); } function selectOwnExistingProduct(idx) { const list = getOwnProductsList(); const p = list[idx]; if (!p) return; selectedOwnProduct = p; document.getElementById('own-name').value = p.name || ''; const catSel = document.getElementById('own-category'); if (catSel && [...catSel.options].some(o => o.value === p.category)) catSel.value = p.category; updateOwnSizeOptions(); document.getElementById('own-color').value = (p.colors && p.colors[0]) ? (p.colors[0].name || '') : ''; document.getElementById('own-desc').value = p.desc || ''; const uniqueImgs = []; (p.colors || []).forEach(c => { if (c && c.image && !uniqueImgs.includes(c.image) && uniqueImgs.length < 3) uniqueImgs.push(c.image); }); ownPhotos = uniqueImgs.map(u => ({ url: u, fileId: extractDriveIdClient(u), base64: '', modified: false })); renderOwnPhotoSlots(); document.getElementById('own-selected-text').innerText = `✅ ရွေးထားသည်: ${p.name} (လက်ကျန် ${p.totalStock || 0} ခု)`; document.getElementById('own-selected-banner').classList.remove('hidden'); onOwnSizeChanged(); renderOwnExistingPicker(); } function clearOwnSelection(resetInputs) { selectedOwnProduct = null; document.getElementById('own-selected-banner')?.classList.add('hidden'); document.getElementById('own-current-stk')?.classList.add('hidden'); if (resetInputs) { ['own-name', 'own-price', 'own-color', 'own-desc'].forEach(id => { const el = document.getElementById(id); if (el) el.value = ''; }); document.getElementById('own-qty').value = '10'; document.getElementById('own-qty-mode').value = 'add'; ownPhotos = []; renderOwnPhotoSlots(); } renderOwnExistingPicker(); } function updateOwnSizeOptions() { const cat = document.getElementById('own-category')?.value || 'ဝမ်းဆက်'; const sizeSel = document.getElementById('own-size'); if (!sizeSel) return; if (AGE_REQUIRED_CATS.includes(cat)) { sizeSel.innerHTML = SIZE_LABELS.map(sz => `<option value="${escapeHtml(sz)}">${escapeHtml(sz)}</option>`).join(''); } else { sizeSel.innerHTML = `<option value="အသက်မလို">အသက်မလို</option>`; } onOwnSizeChanged(); } function onOwnSizeChanged() { const badge = document.getElementById('own-current-stk'); if (!selectedOwnProduct) { if (badge) badge.classList.add('hidden'); return; } const cat = document.getElementById('own-category')?.value || ''; const sz = document.getElementById('own-size')?.value || ''; const idx = AGE_REQUIRED_CATS.includes(cat) ? Math.max(0, SIZE_LABELS.indexOf(sz)) : 0; const curStk = (selectedOwnProduct.stocks && selectedOwnProduct.stocks[idx]) || 0; const curPr = (selectedOwnProduct.prices && selectedOwnProduct.prices[idx]) || 0; const validPrices = (selectedOwnProduct.prices || []).filter(v => v > 0); const fallbackPr = validPrices.length > 0 ? validPrices[0] : 0; if (badge) { badge.innerText = `လက်ရှိ: ${curStk} ခု`; badge.classList.remove('hidden'); } const prInput = document.getElementById('own-price'); if (prInput && (curPr > 0 || fallbackPr > 0)) prInput.value = curPr > 0 ? curPr : fallbackPr; } function renderOwnPhotoSlots() { const box = document.getElementById('own-photo-slots'); const cnt = document.getElementById('own-photo-count'); const addBtn = document.getElementById('btn-own-add-photo'); if (cnt) cnt.innerText = `${ownPhotos.length} / 3 ပုံ`; if (!box) return; if (ownPhotos.length === 0) { box.innerHTML = `<div class="bg-pink-50/60 border-2 border-dashed border-pink-200 rounded-xl p-4 text-center text-xs text-gray-500 font-bold">ပုံမထည့်ရသေးပါ (၁ ပုံ မှ ၃ ပုံအထိ ထည့်နိုင်သည်)</div>`; } else { box.innerHTML = ownPhotos.map((ph, idx) => { const src = ph.base64 || ph.url || './icon.png?v=3'; return ` <div class="bg-gray-50 border border-pink-200 rounded-xl p-2 flex items-center gap-2.5"> <div class="relative w-16 h-16 rounded-lg overflow-hidden border bg-white shrink-0"> <img src="${escapeHtml(src)}" class="w-full h-full object-contain"> <span class="absolute bottom-0 left-0 bg-black/70 text-white text-[8px] font-extrabold px-1">${idx === 0 ? 'ပုံ ၁' : 'ပုံ ' + (idx + 1)}</span> </div> <div class="flex-1 flex flex-wrap gap-1.5"> <button type="button" onclick="aiRemoveBgPhotoByTarget('own', ${idx}, this)" class="bg-pink-600 hover:bg-pink-700 text-white text-[11px] font-extrabold px-2.5 py-1 rounded-lg">✨ AI နောက်ခံဖြတ်</button> <button type="button" onclick="openWhiteEraserModal(${idx}, 'own')" class="bg-emerald-100 hover:bg-emerald-200 text-emerald-900 border border-emerald-300 text-[11px] font-extrabold px-2.5 py-1 rounded-lg">🖌️ ခဲဖျက်</button> <button type="button" onclick="removeOwnPhoto(${idx})" class="bg-red-100 hover:bg-red-200 text-red-700 text-[11px] font-extrabold px-2 py-1 rounded-lg">🗑️ ဖျက်</button> </div> </div> `; }).join(''); } if (addBtn) { const isFull = ownPhotos.length >= 3; addBtn.disabled = isFull; addBtn.innerText = isFull ? '✅ ၃ ပုံ ပြည့်ပါပြီ' : `🖼️ Gallery မှ ပုံရွေးမည် (ကျန် ${3 - ownPhotos.length} ပုံ)`; } } async function handleOwnAddPhotos(event) { const files = Array.from(event.target.files || []); event.target.value = ''; if (!files.length) return; const remain = 3 - ownPhotos.length; if (remain <= 0) return; document.getElementById('own-photo-status').innerText = '⏳ ပုံပြင်ဆင်နေ...'; for (const f of files.slice(0, remain)) { const b64 = await compressAdminImageFile(f); if (b64) ownPhotos.push({ url: '', fileId: '', base64: b64, modified: true }); } document.getElementById('own-photo-status').innerText = '✅ ပုံထည့်ပြီးပါပြီ'; renderOwnPhotoSlots(); } function removeOwnPhoto(idx) { ownPhotos.splice(idx, 1); renderOwnPhotoSlots(); } async function submitAdminOwnProduct(e) { e.preventDefault(); const prodName = (document.getElementById('own-name')?.value || '').trim(); if (!prodName) return; const btn = document.getElementById('btn-own-submit'); btn.disabled = true; btn.innerText = '⏳ Google Sheet ထဲ သိမ်းဆည်းနေပါသည်...'; const qtyMode = document.getElementById('own-qty-mode')?.value || 'add'; const qtyNum = Math.max(0, parseInt(document.getElementById('own-qty')?.value, 10) || 0); const photoList = ownPhotos.slice(0, 3).map(p => ({ base64: p.base64 || '', url: p.base64 ? '' : (p.url || '') })); const payload = { action: 'adminSaveOwnProduct', productName: prodName, category: document.getElementById('own-category')?.value || 'အင်္ကျီ', size: document.getElementById('own-size')?.value || 'အသက်မလို', price: parseInt(document.getElementById('own-price')?.value, 10) || 0, color: (document.getElementById('own-color')?.value || '').trim(), description: (document.getElementById('own-desc')?.value || '').trim(), photoList: photoList }; if (qtyMode === 'exact') payload.exactStock = qtyNum; else payload.qty = Math.max(1, qtyNum); try { await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify(payload) }); clearOwnSelection(true); showBannerNoti('✅ OWN Stock သိမ်းပြီးပါပြီ!', `${prodName} ကို Google Sheet နှင့် ဝယ်သူ App ထဲ ထည့်သွင်းပြီးပါပြီ။`); setTimeout(() => { loadProducts(true); loadAdminDashboard(true); }, 1500); } catch (err) { alert('⚠️ သိမ်းဆည်းရာတွင် အင်တာနက်ချိတ်ဆက်မှု စစ်ဆေးပေးပါ။'); } btn.disabled = false; btn.innerText = '💾 OWN Stock သိမ်းဆည်းမည် (Sheet + App)'; } // ==================== ADMIN DASHBOARD DATA & RENDERING ==================== async function loadAdminDashboard(silent = false) { const btn = document.getElementById('btn-admin-refresh'); if (btn && !silent) btn.innerText = '⏳...'; try { const res = await fetch(`${APPS_SCRIPT_URL}?action=getVisitors&t=${Date.now()}`, { cache: 'no-store' }); const data = await res.json(); adminDataCache = data; if (data && data.sheetUrl) { try { localStorage.setItem('mt_master_sheet_url', data.sheetUrl); } catch (e) {} } renderAdminOrdersAndRiders(); } catch (e) {} if (btn && !silent) btn.innerText = '🔄 ပြန်စစ်'; } function parseOrderItemsForAdmin(ord) { let arr = []; if (ord.itemsJson) { try { arr = JSON.parse(ord.itemsJson); } catch (e) { arr = []; } } if (arr.length > 0) { return arr.map(it => ({ name: it.name || '', colorName: it.colorName || '', size: it.size || '', qty: Number(it.qty || 1), price: Number(it.price || 0), image: it.image || lookupProductImage(it.name, it.colorName), shopId: normalizeShopId(it.shopId) })); } const lines = (ord.itemsText || '').split('\n').filter(Boolean); return lines.map(line => { const clean = line.replace(/^\d+\.\s*/, ''); const m = clean.match(/^(.+?)\s*\[အရောင်:\s*(.*?)\s*\|\s*အရွယ်:\s*(.*?)\]\s*x\s*(\d+)/); if (m) { return { name: m[1].trim(), colorName: m[2].trim(), size: m[3].trim(), qty: parseInt(m[4], 10) || 1, price: 0, image: lookupProductImage(m[1].trim(), m[2].trim()), shopId: 'OWN' }; } return { name: clean, colorName: '', size: '', qty: 1, price: 0, image: '', shopId: 'OWN' }; }); } function getPackingChecks() { try { return JSON.parse(localStorage.getItem('mt_admin_packing_checks') || '{}'); } catch (e) { return {}; } } function togglePackingCheck(key) { const checks = getPackingChecks(); if (checks[key]) delete checks[key]; else checks[key] = true; try { localStorage.setItem('mt_admin_packing_checks', JSON.stringify(checks)); } catch (e) {} renderAdminOrdersAndRiders(); } function openAdminItemPreview(key) { const info = window.__adminPreviewMap[key]; if (!info) return; activePreviewInfo = info; const imgEl = document.getElementById('aip-img'); imgEl.dataset.fallbackTried = ''; const cached = info.fileId && window.__b64ImgCache[info.fileId]; imgEl.src = cached ? cached.dataUrl : (info.image || './icon.png?v=3'); if (info.fileId) imgEl.onerror = () => loadDriveImageFallback(imgEl, info.fileId); else imgEl.onerror = null; document.getElementById('aip-title').innerText = info.name || ''; const priceText = Number(info.price || 0) > 0 ? ` | 💰 ${Number(info.price).toLocaleString()} Ks` : ''; const szText = info.size && info.size !== 'အသက်မလို' ? ` | 📏 ${info.size}` : ''; document.getElementById('aip-meta').innerText = `[${info.shopId || ''}] 🎨 ${info.colorName || '-'}${szText} | 📦 x ${info.qty || 1} ခု${priceText}`; const dlBtn = document.getElementById('aip-download-btn'); if (info.allowDownload && (info.fileId || info.image)) dlBtn.classList.remove('hidden'); else dlBtn.classList.add('hidden'); document.getElementById('admin-item-preview-modal').classList.remove('hidden'); } function downloadFromPreviewModal(btnEl) { if (!activePreviewInfo) return; downloadRestockImage(activePreviewInfo.fileId || '', activePreviewInfo.image || '', activePreviewInfo.name || 'product', btnEl); } function closeAdminItemPreview() { document.getElementById('admin-item-preview-modal').classList.add('hidden'); } // ==================== ADMIN RESTOCK FULL EDITOR ==================== function getRestockImagesArray(rs) { if (Array.isArray(rs.images) && rs.images.length > 0) return rs.images.filter(Boolean).slice(0, MAX_ADMIN_RESTOCK_PHOTOS); return rs.image ? [rs.image] : []; } function updateAdminRestockEditSizes(selectedSize) { const cat = document.getElementById('re-edit-category')?.value || 'အင်္ကျီ'; const szSel = document.getElementById('re-edit-size'); if (!szSel) return; if (AGE_REQUIRED_CATS.includes(cat)) { szSel.innerHTML = SIZE_LABELS.map(sz => `<option value="${escapeHtml(sz)}">${escapeHtml(sz)}</option>`).join(''); if (selectedSize && SIZE_LABELS.includes(selectedSize)) szSel.value = selectedSize; } else { szSel.innerHTML = `<option value="အသက်မလို">အသက်မလို</option>`; szSel.value = 'အသက်မလို'; } } function openRestockEditModal(requestId) { const rs = (adminDataCache?.pendingRestocks || []).find(x => x.requestId === requestId); if (!rs) return; editingRestockId = requestId; const imgs = getRestockImagesArray(rs); const fIds = Array.isArray(rs.fileIds) ? rs.fileIds : []; editingRestockPhotos = imgs.map((u, i) => ({ url: u, fileId: fIds[i] || extractDriveIdClient(u), base64: '', modified: false })); document.getElementById('re-product-title').innerText = `🏪 ${rs.shopId} — ${rs.shopName} (${rs.requestId})`; document.getElementById('re-edit-name').value = rs.productName || ''; const catSel = document.getElementById('re-edit-category'); const catsOnly = CATEGORY_LIST.filter(c => c !== 'အားလုံး' && c !== '🔥 Trending'); catSel.innerHTML = catsOnly.map(c => `<option value="${escapeHtml(c)}">${escapeHtml(c)}</option>`).join(''); const mappedCat = mapLegacyCatClient(rs.category || 'အင်္ကျီ'); catSel.value = catsOnly.includes(mappedCat) ? mappedCat : 'အင်္ကျီ'; updateAdminRestockEditSizes(rs.size || 'အသက်မလို'); document.getElementById('re-edit-qty').value = Number(rs.qty || 1); document.getElementById('re-edit-price').value = Number(rs.price || 0); document.getElementById('re-edit-color').value = rs.color || ''; document.getElementById('re-edit-desc').value = rs.description || ''; document.getElementById('re-edit-status').innerText = ''; renderAdminRestockEditSlots(); document.getElementById('admin-restock-edit-modal').classList.remove('hidden'); } function closeRestockEditModal() { document.getElementById('admin-restock-edit-modal').classList.add('hidden'); editingRestockId = ''; editingRestockPhotos = []; replacePhotoTargetIdx = -1; } function renderAdminRestockEditSlots() { const box = document.getElementById('re-photo-slots'); const addBtn = document.getElementById('btn-re-add-photo'); const cntBadge = document.getElementById('re-photo-count'); if (cntBadge) cntBadge.innerText = `${editingRestockPhotos.length} / ${MAX_ADMIN_RESTOCK_PHOTOS} ပုံ`; if (!box) return; if (editingRestockPhotos.length === 0) { box.innerHTML = `<div class="bg-gray-50 border-2 border-dashed border-gray-300 rounded-2xl p-6 text-center text-xs text-gray-500 font-bold">ပုံမရှိသေးပါ — "➕ Gallery မှ ပုံထပ်ထည့်မည်" ကို နှိပ်၍ ထည့်နိုင်ပါသည်။</div>`; } else { box.innerHTML = editingRestockPhotos.map((ph, idx) => { const cached = ph.fileId && window.__b64ImgCache[ph.fileId]; const src = ph.base64 || (cached ? cached.dataUrl : ph.url) || './icon.png?v=3'; return ` <div class="bg-gray-50 border-2 ${idx === 0 ? 'border-amber-400' : 'border-gray-200'} rounded-2xl p-2.5 flex items-center gap-3"> <div class="relative w-20 h-20 rounded-xl overflow-hidden border bg-white shrink-0"> <img src="${escapeHtml(src)}" ${!ph.base64 && ph.fileId ? `onerror="loadDriveImageFallback(this, '${escapeHtml(ph.fileId)}')"` : ''} class="w-full h-full object-contain"> <span class="absolute bottom-0.5 left-0.5 bg-black/75 text-white text-[9px] font-extrabold px-1.5 py-0.5 rounded">${idx === 0 ? 'ပုံ ၁ (အဓိက)' : 'ပုံ ' + (idx + 1)}</span> </div> <div class="flex-1 min-w-0 space-y-1.5"> <div class="flex flex-wrap items-center gap-1"> ${ph.modified ? `<span class="bg-emerald-100 text-emerald-800 text-[10px] font-extrabold px-2 py-0.5 rounded-full">✨ ပြင်ဆင်ပြီး</span>` : `<span class="bg-amber-100 text-amber-900 text-[10px] font-bold px-2 py-0.5 rounded-full">မူရင်းပုံ</span>`} </div> <div class="flex flex-wrap gap-1.5"> <button type="button" onclick="aiRemoveBgPhotoByTarget('restock', ${idx}, this)" class="bg-pink-600 hover:bg-pink-700 text-white text-[11px] font-extrabold px-2.5 py-1 rounded-lg shadow-sm">✨ AI နောက်ခံဖြတ်</button> <button type="button" onclick="openWhiteEraserModal(${idx}, 'restock')" class="bg-emerald-100 hover:bg-emerald-200 text-emerald-900 border border-emerald-300 text-[11px] font-extrabold px-2.5 py-1 rounded-lg">🖌️ ခဲဖျက်</button> <button type="button" onclick="triggerReplaceRestockPhoto(${idx})" class="bg-blue-600 hover:bg-blue-700 text-white text-[11px] font-extrabold px-2.5 py-1 rounded-lg">🔄 ပုံလဲ</button> <button type="button" onclick="transformAdminRestockPhoto(${idx}, 'rotate', this)" class="bg-purple-100 hover:bg-purple-200 text-purple-900 text-[11px] font-extrabold px-2.5 py-1 rounded-lg">↪️ 90°</button> <button type="button" onclick="transformAdminRestockPhoto(${idx}, 'square', this)" class="bg-white hover:bg-gray-100 text-gray-800 border border-gray-300 text-[11px] font-extrabold px-2.5 py-1 rounded-lg">⬜ 1:1</button> ${idx > 0 ? `<button type="button" onclick="moveRestockPhotoFirst(${idx})" class="bg-amber-100 hover:bg-amber-200 text-amber-900 text-[11px] font-extrabold px-2.5 py-1 rounded-lg">⭐ အဓိက</button>` : ''} <button type="button" onclick="removeAdminRestockPhoto(${idx})" class="bg-red-100 hover:bg-red-200 text-red-700 text-[11px] font-extrabold px-2.5 py-1 rounded-lg">🗑️</button> </div> </div> </div> `; }).join(''); } if (addBtn) { const isFull = editingRestockPhotos.length >= MAX_ADMIN_RESTOCK_PHOTOS; addBtn.disabled = isFull; addBtn.className = isFull ? 'bg-gray-200 text-gray-500 font-extrabold text-xs px-3.5 py-2 rounded-xl cursor-not-allowed' : 'bg-amber-100 hover:bg-amber-200 text-amber-900 font-extrabold text-xs px-3.5 py-2 rounded-xl border border-amber-300'; addBtn.innerText = isFull ? '✅ ၃ ပုံ ပြည့်ပါပြီ' : `➕ Gallery မှ ပုံထပ်ထည့်မည် (ကျန် ${MAX_ADMIN_RESTOCK_PHOTOS - editingRestockPhotos.length} ပုံ)`; } } function compressAdminImageFile(file) { return new Promise((resolve) => { const reader = new FileReader(); reader.onload = function(ev) { const img = new Image(); img.onload = function() { const maxDim = 800; let w = img.width, h = img.height; if (w > maxDim || h > maxDim) { if (w > h) { h = Math.round(h * (maxDim / w)); w = maxDim; } else { w = Math.round(w * (maxDim / h)); h = maxDim; } } const canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h; const ctx = canvas.getContext('2d'); ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, w, h); ctx.drawImage(img, 0, 0, w, h); resolve(canvas.toDataURL('image/jpeg', 0.72)); }; img.onerror = () => resolve(''); img.src = ev.target.result; }; reader.onerror = () => resolve(''); reader.readAsDataURL(file); }); } async function handleAdminAddRestockPhotos(event) { const files = Array.from(event.target.files || []); event.target.value = ''; if (!files.length) return; const remain = MAX_ADMIN_RESTOCK_PHOTOS - editingRestockPhotos.length; if (remain <= 0) return; document.getElementById('re-edit-status').innerText = '⏳ ပုံပြင်ဆင်နေ...'; for (const f of files.slice(0, remain)) { const b64 = await compressAdminImageFile(f); if (b64) editingRestockPhotos.push({ url: '', fileId: '', base64: b64, modified: true }); } document.getElementById('re-edit-status').innerText = '✅ ပုံထည့်ပြီးပါပြီ'; renderAdminRestockEditSlots(); } function triggerReplaceRestockPhoto(idx) { replacePhotoTargetIdx = idx; document.getElementById('re-replace-photo-file').click(); } async function handleAdminReplaceRestockPhoto(event) { const file = event.target.files && event.target.files[0]; event.target.value = ''; if (!file || replacePhotoTargetIdx < 0 || !editingRestockPhotos[replacePhotoTargetIdx]) return; document.getElementById('re-edit-status').innerText = '⏳ ပုံအသစ်ပြင်ဆင်နေ...'; const b64 = await compressAdminImageFile(file); if (b64) { editingRestockPhotos[replacePhotoTargetIdx] = { url: '', fileId: '', base64: b64, modified: true }; document.getElementById('re-edit-status').innerText = '✅ ပုံအသစ်လဲပြီးပါပြီ'; renderAdminRestockEditSlots(); } replacePhotoTargetIdx = -1; } function moveRestockPhotoFirst(idx) { if (idx <= 0 || idx >= editingRestockPhotos.length) return; const [picked] = editingRestockPhotos.splice(idx, 1); editingRestockPhotos.unshift(picked); renderAdminRestockEditSlots(); } function removeAdminRestockPhoto(idx) { editingRestockPhotos.splice(idx, 1); renderAdminRestockEditSlots(); } async function ensureEditablePhotoBase64(ph) { if (ph.base64) return ph.base64; if (ph.fileId) { if (window.__b64ImgCache[ph.fileId]?.dataUrl) return window.__b64ImgCache[ph.fileId].dataUrl; const res = await fetch(`${APPS_SCRIPT_URL}?action=getImageBase64&fileId=${encodeURIComponent(ph.fileId)}&t=${Date.now()}`, { cache: 'no-store' }); const data = await res.json(); if (data && data.status === 'ok' && data.dataUrl) { window.__b64ImgCache[ph.fileId] = data; return data.dataUrl; } } if (ph.url) { const resp = await fetch(ph.url); const blob = await resp.blob(); return await new Promise((resolve) => { const r = new FileReader(); r.onload = () => resolve(r.result || ''); r.onerror = () => resolve(''); r.readAsDataURL(blob); }); } return ''; } async function transformAdminRestockPhoto(idx, mode, btnEl) { const ph = editingRestockPhotos[idx]; if (!ph) return; const origTxt = btnEl ? btnEl.innerText : ''; if (btnEl) { btnEl.disabled = true; btnEl.innerText = '⏳...'; } document.getElementById('re-edit-status').innerText = '⏳ ပုံပြုပြင်နေပါသည်...'; try { const srcB64 = await ensureEditablePhotoBase64(ph); if (!srcB64) throw new Error('no_image'); const newB64 = await new Promise((resolve, reject) => { const img = new Image(); img.onload = function() { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); if (mode === 'rotate') { canvas.width = img.height; canvas.height = img.width; ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.translate(canvas.width / 2, canvas.height / 2); ctx.rotate(Math.PI / 2); ctx.drawImage(img, -img.width / 2, -img.height / 2); } else { const side = Math.min(800, Math.max(img.width, img.height, 600)); canvas.width = side; canvas.height = side; ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, side, side); const pad = Math.round(side * 0.05); const maxBox = side - pad * 2; const ratio = Math.min(maxBox / img.width, maxBox / img.height); const dw = Math.round(img.width * ratio); const dh = Math.round(img.height * ratio); ctx.drawImage(img, Math.round((side - dw) / 2), Math.round((side - dh) / 2), dw, dh); } resolve(canvas.toDataURL('image/jpeg', 0.76)); }; img.onerror = reject; img.src = srcB64; }); editingRestockPhotos[idx].base64 = newB64; editingRestockPhotos[idx].modified = true; document.getElementById('re-edit-status').innerText = mode === 'rotate' ? '✅ 90° လှည့်ပြီးပါပြီ' : '✅ 1:1 အဖြူရောင်နောက်ခံ ပြင်ပြီးပါပြီ'; renderAdminRestockEditSlots(); } catch (e) { alert('⚠️ ဤပုံကို တိုက်ရိုက်ပြင်မရပါ — "🔄 ပုံလဲ" ဖြင့် ထည့်နိုင်ပါသည်။'); if (btnEl) { btnEl.disabled = false; btnEl.innerText = origTxt; } } } // ==================== SHARED AI BG REMOVAL + WHITE ERASER (RESTOCK & OWN) ==================== let aiBgRemoveModulePromise = null; let eraserPhotoIdx = -1; let eraserTargetType = 'restock'; let eraserIsDrawing = false; let eraserLastPos = null; let eraserUndoStack = []; async function aiRemoveBgPhotoByTarget(targetType, idx, btnEl) { const listRef = targetType === 'own' ? ownPhotos : editingRestockPhotos; const ph = listRef[idx]; if (!ph) return; const origTxt = btnEl ? btnEl.innerText : ''; const statusEl = document.getElementById(targetType === 'own' ? 'own-photo-status' : 're-edit-status'); if (btnEl) { btnEl.disabled = true; btnEl.innerText = '⏳ AI ဖြတ်နေ...'; } if (statusEl) statusEl.innerText = '⏳ AI နောက်ခံဖြတ်နေပါသည် (ခဏစောင့်ပါ)...'; try { const srcB64 = await ensureEditablePhotoBase64(ph); if (!srcB64) throw new Error('no_image'); if (!aiBgRemoveModulePromise) { aiBgRemoveModulePromise = import('https://esm.sh/@imgly/background-removal@1.4.5'); } const mod = await aiBgRemoveModulePromise; const removeBg = mod.removeBackground || (mod.default && mod.default.removeBackground) || mod.default; if (typeof removeBg !== 'function') throw new Error('ai_load_failed'); const inputBlob = dataUrlToBlob(srcB64); const resultBlob = await removeBg(inputBlob, { progress: (key, current, total) => { if (statusEl && total > 0) { const pct = Math.min(100, Math.round((current / total) * 100)); statusEl.innerText = key && key.includes('fetch') ? `⏳ AI ဖိုင် ဒေါင်းလုဒ်ဆွဲနေ... ${pct}%` : `✨ AI နောက်ခံဖြတ်နေ... ${pct}%`; } } }); const objUrl = URL.createObjectURL(resultBlob); const finalWhiteB64 = await new Promise((resolve, reject) => { const img = new Image(); img.onload = function() { const side = 800; const canvas = document.createElement('canvas'); canvas.width = side; canvas.height = side; const ctx = canvas.getContext('2d'); ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, side, side); const pad = Math.round(side * 0.06); const maxBox = side - pad * 2; const ratio = Math.min(maxBox / img.width, maxBox / img.height); const dw = Math.round(img.width * ratio); const dh = Math.round(img.height * ratio); ctx.drawImage(img, Math.round((side - dw) / 2), Math.round((side - dh) / 2), dw, dh); URL.revokeObjectURL(objUrl); resolve(canvas.toDataURL('image/jpeg', 0.82)); }; img.onerror = (err) => { URL.revokeObjectURL(objUrl); reject(err); }; img.src = objUrl; }); listRef[idx].base64 = finalWhiteB64; listRef[idx].modified = true; if (statusEl) statusEl.innerText = '✅ AI နောက်ခံဖြတ် + အဖြူရောင်နောက်ခံ ပြီးပါပြီ'; if (targetType === 'own') renderOwnPhotoSlots(); else renderAdminRestockEditSlots(); } catch (e) { aiBgRemoveModulePromise = null; if (statusEl) statusEl.innerText = '⚠️ AI နောက်ခံဖြတ် မအောင်မြင်ပါ — 🖌️ ခဲဖျက်ဖြင့် ဖျက်နိုင်ပါသည်။'; if (btnEl) { btnEl.disabled = false; btnEl.innerText = origTxt; } } } function getEraserCanvasPos(ev) { const canvas = document.getElementById('eraser-canvas'); const rect = canvas.getBoundingClientRect(); return { x: (ev.clientX - rect.left) * (canvas.width / rect.width), y: (ev.clientY - rect.top) * (canvas.height / rect.height) }; } function bindWhiteEraserCanvasEvents() { const canvas = document.getElementById('eraser-canvas'); if (!canvas || canvas.dataset.bound === '1') return; canvas.dataset.bound = '1'; canvas.addEventListener('pointerdown', (ev) => { ev.preventDefault(); const ctx = canvas.getContext('2d'); if (eraserUndoStack.length >= 15) eraserUndoStack.shift(); eraserUndoStack.push(ctx.getImageData(0, 0, canvas.width, canvas.height)); eraserIsDrawing = true; const pos = getEraserCanvasPos(ev); eraserLastPos = pos; const brushSize = parseInt(document.getElementById('eraser-brush-size')?.value, 10) || 30; ctx.fillStyle = '#ffffff'; ctx.beginPath(); ctx.arc(pos.x, pos.y, brushSize / 2, 0, Math.PI * 2); ctx.fill(); try { canvas.setPointerCapture(ev.pointerId); } catch (e) {} }); canvas.addEventListener('pointermove', (ev) => { if (!eraserIsDrawing) return; ev.preventDefault(); const ctx = canvas.getContext('2d'); const pos = getEraserCanvasPos(ev); const brushSize = parseInt(document.getElementById('eraser-brush-size')?.value, 10) || 30; ctx.strokeStyle = '#ffffff'; ctx.lineWidth = brushSize; ctx.lineCap = 'round'; ctx.lineJoin = 'round'; ctx.beginPath(); ctx.moveTo(eraserLastPos.x, eraserLastPos.y); ctx.lineTo(pos.x, pos.y); ctx.stroke(); eraserLastPos = pos; }); const stopDraw = () => { eraserIsDrawing = false; eraserLastPos = null; }; canvas.addEventListener('pointerup', stopDraw); canvas.addEventListener('pointercancel', stopDraw); } async function openWhiteEraserModal(idx, targetType = 'restock') { eraserTargetType = targetType; const listRef = targetType === 'own' ? ownPhotos : editingRestockPhotos; const ph = listRef[idx]; if (!ph) return; try { const srcB64 = await ensureEditablePhotoBase64(ph); if (!srcB64) throw new Error('no_image'); eraserPhotoIdx = idx; eraserUndoStack = []; const img = new Image(); img.onload = function() { const canvas = document.getElementById('eraser-canvas'); const maxDim = 800; let w = img.width, h = img.height; if (w > maxDim || h > maxDim) { if (w > h) { h = Math.round(h * (maxDim / w)); w = maxDim; } else { w = Math.round(w * (maxDim / h)); h = maxDim; } } canvas.width = w; canvas.height = h; const ctx = canvas.getContext('2d'); ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, w, h); ctx.drawImage(img, 0, 0, w, h); bindWhiteEraserCanvasEvents(); document.getElementById('admin-photo-eraser-modal').classList.remove('hidden'); }; img.onerror = () => alert('⚠️ ပုံဖွင့်မရပါ။'); img.src = srcB64; } catch (e) { alert('⚠️ ဤပုံကို ခဲဖျက်ဖြင့် ဖွင့်မရပါ။'); } } function undoWhiteEraser() { if (!eraserUndoStack.length) return; const canvas = document.getElementById('eraser-canvas'); canvas.getContext('2d').putImageData(eraserUndoStack.pop(), 0, 0); } function closeWhiteEraserModal() { document.getElementById('admin-photo-eraser-modal').classList.add('hidden'); eraserPhotoIdx = -1; eraserUndoStack = []; } function saveWhiteEraserPhoto() { const listRef = eraserTargetType === 'own' ? ownPhotos : editingRestockPhotos; if (eraserPhotoIdx < 0 || !listRef[eraserPhotoIdx]) return; const canvas = document.getElementById('eraser-canvas'); listRef[eraserPhotoIdx].base64 = canvas.toDataURL('image/jpeg', 0.82); listRef[eraserPhotoIdx].modified = true; closeWhiteEraserModal(); if (eraserTargetType === 'own') { document.getElementById('own-photo-status').innerText = '✅ ခဲဖျက်ဖြင့် ပြင်ပြီးသားပုံ သိမ်းပြီး'; renderOwnPhotoSlots(); } else { document.getElementById('re-edit-status').innerText = '✅ ခဲဖျက်ဖြင့် ပြင်ပြီးသားပုံ သိမ်းပြီး'; renderAdminRestockEditSlots(); } } async function saveEditedRestockRequest(andApprove, btnEl) { if (!editingRestockId) return; const editedName = (document.getElementById('re-edit-name')?.value || '').trim(); if (!editedName) { alert('⚠️ ပစ္စည်းအမည် ထည့်သွင်းပေးပါ။'); return; } if (andApprove && !confirm('ပြင်ဆင်မှုများကို သိမ်းဆည်းပြီး ဝယ်သူ App နှင့် Google Sheet ထဲသို့ Approve ထည့်သွင်းပါမည်လား?')) return; const btnSave = document.getElementById('btn-re-save-only'); const btnApp = document.getElementById('btn-re-save-approve'); if (btnSave) btnSave.disabled = true; if (btnApp) btnApp.disabled = true; if (btnEl) btnEl.innerText = andApprove ? '⏳ Approve ထည့်နေ...' : '⏳ သိမ်းနေ...'; const photoList = editingRestockPhotos.slice(0, MAX_ADMIN_RESTOCK_PHOTOS).map(ph => ({ base64: ph.base64 || '', url: ph.base64 ? '' : (ph.url || '') })); try { await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: andApprove ? 'adminApproveRestock' : 'adminUpdateRestockDetails', requestId: editingRestockId, productName: editedName, category: document.getElementById('re-edit-category')?.value || 'အင်္ကျီ', size: document.getElementById('re-edit-size')?.value || 'အသက်မလို', qty: Math.max(1, parseInt(document.getElementById('re-edit-qty')?.value, 10) || 1), price: parseInt(document.getElementById('re-edit-price')?.value, 10) || 0, color: (document.getElementById('re-edit-color')?.value || '').trim(), description: (document.getElementById('re-edit-desc')?.value || '').trim(), photoList: photoList }) }); closeRestockEditModal(); showBannerNoti( andApprove ? '✅ Approve ပြီးပါပြီ' : '💾 ပြင်ဆင်မှု သိမ်းပြီးပါပြီ', andApprove ? 'ဝယ်သူ App နှင့် Google Sheet ထဲသို့ ထည့်သွင်းပြီးပါပြီ။' : 'Approve မလုပ်မီ ပုံနှင့်အချက်အလက်များ သိမ်းဆည်းပြီးပါပြီ။' ); setTimeout(() => { loadAdminDashboard(false); if (andApprove) loadProducts(true); }, 1600); } catch (e) { alert('⚠️ သိမ်းဆည်းရာတွင် အင်တာနက်ချိတ်ဆက်မှု စစ်ဆေးပေးပါ။'); } if (btnSave) { btnSave.disabled = false; btnSave.innerText = '💾 ပြင်ဆင်မှု သိမ်းမည်'; } if (btnApp) { btnApp.disabled = false; btnApp.innerText = '✅ သိမ်းပြီး ဝယ်သူ App ထဲ Approve ထည့်မည်'; } } function openRejectRestockModal(requestId) { const rs = (adminDataCache?.pendingRestocks || []).find(x => x.requestId === requestId); if (!rs) return; rejectingRestockId = requestId; document.getElementById('rej-modal-info').innerText = `🏪 ${rs.shopId} (${rs.shopName}) — ${rs.productName} (+${rs.qty} ခု)`; document.getElementById('rej-reason-input').value = ''; document.getElementById('rej-reason-err').classList.add('hidden'); document.getElementById('admin-reject-restock-modal').classList.remove('hidden'); setTimeout(() => document.getElementById('rej-reason-input').focus(), 100); } function closeRejectRestockModal() { document.getElementById('admin-reject-restock-modal').classList.add('hidden'); rejectingRestockId = ''; } function setQuickRejectReason(txt) { document.getElementById('rej-reason-input').value = txt; document.getElementById('rej-reason-err').classList.add('hidden'); } async function confirmAdminRejectRestock() { if (!rejectingRestockId) return; const reason = (document.getElementById('rej-reason-input').value || '').trim(); const errEl = document.getElementById('rej-reason-err'); if (!reason) { errEl.classList.remove('hidden'); return; } errEl.classList.add('hidden'); const btn = document.getElementById('btn-confirm-reject-restock'); btn.disabled = true; btn.innerText = '⏳ ပယ်ချနေသည်...'; try { await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: 'adminRejectRestock', requestId: rejectingRestockId, rejectReason: reason }) }); closeRejectRestockModal(); showBannerNoti('❌ ပယ်ချပြီးပါပြီ', `ဆိုင် App ထံ အကြောင်းပြချက် (${reason}) ပေးပို့ပြီးပါပြီ။`); setTimeout(() => loadAdminDashboard(false), 900); } catch (e) { alert('⚠️ အင်တာနက်ချိတ်ဆက်မှု စစ်ဆေးပေးပါ။'); } btn.disabled = false; btn.innerText = '❌ ပယ်ချပြီး ဆိုင်ထံပို့မည်'; } // ==================== 6-STEP ORDER PROCESS BAR (1-6) ==================== function buildAdminOrderProcessSteps(ord, hasPartner) { const st = (ord.status || '').trim(); const pSt = (ord.pickupStatus || '').trim(); const meta = ord.shopMeta || {}; const isDelivered = (st === 'ပို့ပြီး'); const isCodPaid = (st === 'COD ငွေပေးချေပြီး'); const isOnWay = (st === 'ပို့ဆောင်နေပြီ'); const isShopPacked = !!(meta.shopPacked || pSt === 'ဆိုင်မှ ထုပ်ပိုးပြီး (ကောက်ရန်အသင့်)'); const isPickupGoing = (pSt === 'ဆိုင်သို့ သွားနေပါသည်'); const isPicked = (pSt === 'ဆိုင်မှ ပစ္စည်းကောက်ပြီးပြီ' || !!meta.adminPickupConfirmed); const pRider = (ord.pickupRiderName || '').trim(); const dRider = (ord.riderName || '').trim(); let steps = []; if (hasPartner) { const s3Label = pRider ? `Pickup လုပ်ရန် (${escapeHtml(pRider)}) သွားနေပြီ` : 'Pickup သွားနေပြီ'; const s5Label = dRider ? `Delivery (${escapeHtml(dRider)}) ပို့နေပြီ` : 'Delivery ပို့နေပြီ'; steps = [ { num: '၁', label: 'အော်ဒါအသစ်', state: 'done' }, { num: '၂', label: 'ထုပ်ပိုးပြီး', state: (isPickupGoing || isPicked || isOnWay || isCodPaid || isDelivered) ? 'done' : (isShopPacked ? 'active' : 'pending') }, { num: '၃', label: s3Label, state: (isPicked || isOnWay || isCodPaid || isDelivered) ? 'done' : (isPickupGoing ? 'active' : 'pending') }, { num: '၄', label: 'ဆိုင်မှပစ္စည်းကောက်ပြီးပြီ', state: (isOnWay || isCodPaid || isDelivered) ? 'done' : (isPicked ? 'active' : 'pending') }, { num: '၅', label: s5Label, state: (isCodPaid || isDelivered) ? 'done' : (isOnWay ? 'active' : 'pending') }, { num: '၆', label: 'COD Confirm', state: isDelivered ? 'done' : (isCodPaid ? 'active' : 'pending') } ]; } else { steps = [ { num: '၁', label: 'အော်ဒါအသစ်', state: 'done' }, { num: '၂', label: dRider ? `Delivery (${escapeHtml(dRider)}) ပေးပြီး` : 'Delivery ပေးပြီး', state: (isOnWay || isCodPaid || isDelivered) ? 'done' : (ord.riderId ? 'active' : 'pending') }, { num: '၃', label: 'Delivery ပို့နေပြီ', state: (isCodPaid || isDelivered) ? 'done' : (isOnWay ? 'active' : 'pending') }, { num: '၄', label: 'COD Confirm', state: isDelivered ? 'done' : (isCodPaid ? 'active' : 'pending') } ]; } const itemsHtml = steps.map((s, idx) => { let circleCls = 'bg-gray-200 text-gray-500'; let labelCls = 'text-gray-400 font-bold'; if (s.state === 'done') { circleCls = 'bg-emerald-600 text-white'; labelCls = 'text-emerald-700 font-extrabold'; } else if (s.state === 'active') { circleCls = 'bg-amber-500 text-white ring-2 ring-amber-200 animate-pulse'; labelCls = 'text-amber-800 font-extrabold'; } const nextStep = steps[idx + 1]; const lineDone = nextStep && (s.state === 'done' && (nextStep.state === 'done' || nextStep.state === 'active')); const connectorHtml = idx < steps.length - 1 ? `<div class="flex-1 min-w-[12px] h-1 ${lineDone ? 'bg-emerald-500' : 'bg-gray-200'} rounded-full mx-1"></div>` : ''; return ` <div class="flex items-center gap-1 shrink-0"> <span class="w-5 h-5 rounded-full ${circleCls} text-[10px] font-extrabold flex items-center justify-center shrink-0">${s.num}</span> <span class="text-[10px] ${labelCls} whitespace-nowrap">${s.label}</span> </div> ${connectorHtml} `; }).join(''); return `<div class="bg-gray-50 border border-gray-200 rounded-xl px-2.5 py-1.5 flex items-center justify-between overflow-x-auto no-scrollbar">${itemsHtml}</div>`; } function renderAdminPayoutHistory() { const box = document.getElementById('adm-payouts-history-list'); if (!box || !adminDataCache) return; const allSettled = adminDataCache.settledShopPayouts || []; const shopF = document.getElementById('adm-pay-hist-shop')?.value || 'ALL'; const q = (document.getElementById('adm-pay-hist-search')?.value || '').trim().toLowerCase(); const filtered = allSettled.filter(p => { if (shopF !== 'ALL' && p.shopId !== shopF) return false; if (q && !(p.orderId || '').toLowerCase().includes(q) && !(p.customerName || '').toLowerCase().includes(q) && !(p.shopName || '').toLowerCase().includes(q)) return false; return true; }); if (filtered.length === 0) { box.innerHTML = `<div class="bg-white rounded-2xl border p-8 text-center text-xs text-gray-400">လွန်ခဲ့သော ၇ ရက်အတွင်း ငွေရှင်းပြီး History မရှိသေးပါ။</div>`; return; } const grouped = {}; filtered.forEach(p => { if (!grouped[p.shopId]) grouped[p.shopId] = { shopId: p.shopId, shopName: p.shopName, paymentAccount: p.paymentAccount, totalSettled: 0, list: [] }; grouped[p.shopId].totalSettled += Number(p.payout || 0); grouped[p.shopId].list.push(p); }); box.innerHTML = Object.values(grouped).map(g => ` <div class="bg-white rounded-2xl border-2 border-blue-200 overflow-hidden shadow-sm"> <div class="bg-blue-700 text-white p-3 flex flex-wrap justify-between items-center gap-2"> <div> <h4 class="font-extrabold text-sm">🏪 ${escapeHtml(g.shopId)} — ${escapeHtml(g.shopName)}</h4> <p class="text-[11px] text-blue-100 font-bold">✅ ရှင်းပြီးအော်ဒါ: ${g.list.length} ခု</p> </div> <p class="text-base font-extrabold">${g.totalSettled.toLocaleString()} Ks</p> </div> <div class="divide-y p-3 text-xs"> ${g.list.map(item => ` <div class="py-2 flex flex-wrap justify-between items-center gap-2"> <div class="min-w-0"> <span class="font-extrabold text-gray-900">🧾 ${escapeHtml(item.orderId)}</span> <span class="text-gray-600 font-bold">— ${escapeHtml(item.customerName)}</span> <span class="bg-gray-100 text-gray-600 px-1.5 py-0.5 rounded text-[10px] font-bold ml-1">⏳ ကျန် ${item.daysLeft || 1} ရက်</span> <p class="text-[11px] text-gray-500">💸 ${escapeHtml(item.settledAt)}</p> </div> <span class="font-extrabold text-blue-700 text-sm shrink-0">${Number(item.payout).toLocaleString()} Ks</span> </div> `).join('')} </div> </div> `).join(''); } function renderAdminOrdersAndRiders() { if (!adminDataCache) return; const d = adminDataCache; const orders = d.pendingOrders || []; const restocks = d.pendingRestocks || []; const returns = d.returnOrders || []; const payouts = d.unsettledShopPayouts || []; const settledPayouts = d.settledShopPayouts || []; const riders = d.riders || []; const shops = d.shops || []; const shopsById = {}; shops.forEach(s => { shopsById[s.id] = s; }); const pendingShopReqs = shops.filter(s => s.approvalStatus === 'Pending').length; const shopBadgeEl = document.getElementById('adm-badge-shops'); if (shopBadgeEl) { shopBadgeEl.innerText = pendingShopReqs; shopBadgeEl.classList.toggle('hidden', pendingShopReqs === 0); } const openReturnsCount = returns.filter(r => !r.returnInfo || r.returnInfo.status !== 'closed').length; const unpaidSum = payouts.reduce((s, p) => s + Number(p.payout || 0), 0); document.getElementById('adm-stat-orders').innerText = orders.length; document.getElementById('adm-stat-returns').innerText = openReturnsCount; document.getElementById('adm-stat-own').innerText = Number(d.todayOwnSalesTotal || 0).toLocaleString() + ' Ks'; document.getElementById('adm-stat-comm').innerText = Number(d.todayCommissionTotal || 0).toLocaleString() + ' Ks'; document.getElementById('adm-stat-payout').innerText = unpaidSum.toLocaleString() + ' Ks'; document.getElementById('adm-stat-visitors').innerText = `${d.today || 0} / ${d.total || 0}`; document.getElementById('adm-badge-orders').innerText = orders.length; document.getElementById('adm-badge-restocks').innerText = restocks.length; document.getElementById('adm-badge-returns').innerText = openReturnsCount; document.getElementById('adm-badge-payouts').innerText = payouts.length; document.getElementById('pay-badge-unpaid').innerText = payouts.length; document.getElementById('pay-badge-history').innerText = settledPayouts.length; const fc = d.fcmCounts || { customers: d.fcmSubscribers || 0, riders: 0, shops: 0 }; document.getElementById('adm-fcm-cust').innerText = `🛍️ ဝယ်သူ: ${fc.customers || 0}`; document.getElementById('adm-fcm-rider').innerText = `🚚 Delivery: ${fc.riders || 0}`; document.getElementById('adm-fcm-shop').innerText = `🏪 ဆိုင်: ${fc.shops || 0}`; renderCustomerNotiDropdown(); renderAdminCustomersList(); const bcRiderSel = document.getElementById('bc-rider-target'); if (bcRiderSel) { const prevR = bcRiderSel.value; bcRiderSel.innerHTML = `<option value="all_riders">🚚 Delivery ဝန်ထမ်းအားလုံးထံ ပို့မည်</option>` + riders.map(r => `<option value="rider:${escapeHtml(r.id)}">👤 ${escapeHtml(r.id)} — ${escapeHtml(r.name)}</option>`).join(''); if ([...bcRiderSel.options].some(o => o.value === prevR)) bcRiderSel.value = prevR; } const bcShopSel = document.getElementById('bc-shop-target'); if (bcShopSel) { const prevS = bcShopSel.value; bcShopSel.innerHTML = `<option value="all_shops">🏪 ချိတ်ဆက်ဆိုင်အားလုံးထံ ပို့မည်</option>` + shops.map(s => `<option value="shop:${escapeHtml(s.id)}">🏪 ${escapeHtml(s.id)} — ${escapeHtml(s.name)}</option>`).join(''); if ([...bcShopSel.options].some(o => o.value === prevS)) bcShopSel.value = prevS; } const payHistShopSel = document.getElementById('adm-pay-hist-shop'); if (payHistShopSel) { const prevPH = payHistShopSel.value; payHistShopSel.innerHTML = `<option value="ALL">🏪 ဆိုင်အားလုံး</option>` + shops.map(s => `<option value="${escapeHtml(s.id)}">🏪 ${escapeHtml(s.id)} — ${escapeHtml(s.name)}</option>`).join(''); if ([...payHistShopSel.options].some(o => o.value === prevPH)) payHistShopSel.value = prevPH; } const stkSel = document.getElementById('adm-stock-shop-filter'); if (stkSel) { const prevVal = stkSel.value; stkSel.innerHTML = `<option value="ALL">🏪 ဆိုင်အားလုံး (OWN + ချိတ်ဆိုင်)</option><option value="OWN">🏠 OWN (ကိုယ်ပိုင်စတော့)</option>` + shops.map(s => `<option value="${escapeHtml(s.id)}">🏪 ${escapeHtml(s.id)} — ${escapeHtml(s.name)}</option>`).join(''); if ([...stkSel.options].some(o => o.value === prevVal)) stkSel.value = prevVal; } const catSel = document.getElementById('adm-stock-cat-filter'); if (catSel && catSel.options.length <= 1) { const catsOnly = CATEGORY_LIST.filter(c => c !== 'အားလုံး' && c !== '🔥 Trending'); catSel.innerHTML = `<option value="ALL">📂 အမျိုးအစားအားလုံး</option>` + catsOnly.map(c => `<option value="${escapeHtml(c)}">${escapeHtml(c)}</option>`).join(''); } // ---- TAB 1: COMPACT ORDERS ---- const filteredOrders = orders.filter(o => { const hasPartner = o.shopIds && o.shopIds !== 'OWN'; const isCancelReq = o.status === 'ဝယ်သူ Cancel တောင်းဆိုထားသည်' || (o.shopMeta && o.shopMeta.cancelRequested); const isNoAns = o.status === 'ဖုန်းမကိုင် (နောက်နေ့ပြန်ပို့)'; const isShopPacked = !!(o.shopMeta && o.shopMeta.shopPacked); if (currentAdminOrderFilter === 'cancel_req') return isCancelReq || isNoAns; if (currentAdminOrderFilter === 'packed') return hasPartner && isShopPacked; if (currentAdminOrderFilter === 'need_pickup') return hasPartner && (o.pickupStatus === 'မသတ်မှတ်ရသေး' || o.pickupStatus === 'ဆိုင်မှ ထုပ်ပိုးပြီး (ကောက်ရန်အသင့်)' || o.pickupStatus === 'ဆိုင်မှ ပစ္စည်းသွားကောက်ရန်'); if (currentAdminOrderFilter === 'picking') return hasPartner && o.pickupStatus === 'ဆိုင်သို့ သွားနေပါသည်'; if (currentAdminOrderFilter === 'picked') return (!hasPartner || o.pickupStatus === 'ဆိုင်မှ ပစ္စည်းကောက်ပြီးပြီ') && o.status !== 'ပို့ဆောင်နေပြီ' && o.status !== 'COD ငွေပေးချေပြီး'; if (currentAdminOrderFilter === 'onway') return o.status === 'ပို့ဆောင်နေပြီ'; if (currentAdminOrderFilter === 'cod_wait') return o.status === 'COD ငွေပေးချေပြီး'; return true; }); const checks = getPackingChecks(); window.__adminPreviewMap = {}; const ordersEl = document.getElementById('adm-orders-list'); if (filteredOrders.length === 0) { ordersEl.innerHTML = `<div class="bg-white rounded-2xl border p-8 text-center text-xs text-gray-400">ဤစစ်ထုတ်မှုတွင် အော်ဒါ မရှိသေးပါ။</div>`; } else { ordersEl.innerHTML = filteredOrders.map(o => { const items = parseOrderItemsForAdmin(o); const hasPartner = items.some(it => it.shopId !== 'OWN'); const isCodWait = o.status === 'COD ငွေပေးချေပြီး'; const isCancelReq = o.status === 'ဝယ်သူ Cancel တောင်းဆိုထားသည်' || (o.shopMeta && o.shopMeta.cancelRequested); const isNoAns = o.status === 'ဖုန်းမကိုင် (နောက်နေ့ပြန်ပို့)'; const isShopPacked = !!(o.shopMeta && o.shopMeta.shopPacked); const adminPickupConfirmed = !!(o.shopMeta && o.shopMeta.adminPickupConfirmed); const cardBorder = isCancelReq ? 'border-red-500 bg-red-50/40' : (isCodWait ? 'border-emerald-500 bg-emerald-50/40' : (isShopPacked && !adminPickupConfirmed ? 'border-blue-400 bg-blue-50/20' : 'border-pink-200 bg-white')); const cancelReqBanner = isCancelReq ? `<div class="bg-red-600 text-white rounded-lg px-2.5 py-1.5 flex flex-wrap justify-between items-center gap-1.5 text-[11px] font-extrabold"> <span>⚠️ ဝယ်သူ Cancel: ${escapeHtml((o.shopMeta && o.shopMeta.cancelRequestReason) || 'Cancel')}</span> <button type="button" onclick="adminConfirmCancel('${o.orderId}', ${hasPartner}, this)" class="bg-white text-red-700 px-2.5 py-1 rounded-md text-[11px] font-extrabold">❌ Cancel Confirm</button> </div>` : (isNoAns ? `<div class="bg-orange-500 text-white rounded-lg px-2.5 py-1.5 flex flex-wrap justify-between items-center gap-1.5 text-[11px] font-extrabold"> <span>📞 ဝယ်သူ ဖုန်းမကိုင်ပါ</span> <button type="button" onclick="adminConfirmCancel('${o.orderId}', ${hasPartner}, this)" class="bg-white text-orange-800 px-2.5 py-1 rounded-md text-[11px] font-extrabold">❌ Cancel Confirm</button> </div>` : ''); const rejectBadge = Number(o.codRejectCount || 0) > 0 ? `<div class="bg-red-600 text-white text-[11px] font-extrabold px-2.5 py-1 rounded-lg">⚠️ ယခင် COD ငြင်းဖူးသူ (${o.codRejectCount} ကြိမ်)</div>` : ''; const itemsHtml = items.map((it, idx) => { const chkKey = `${o.orderId}_${idx}`; const isChecked = !!checks[chkKey]; window.__adminPreviewMap[chkKey] = it; const isPartnerItem = it.shopId !== 'OWN'; const shopTag = isPartnerItem ? `<span class="bg-amber-100 text-amber-900 px-1.5 py-0.2 rounded text-[9px] font-extrabold">🏪 ${escapeHtml(it.shopId)}</span>` : `<span class="bg-blue-100 text-blue-800 px-1.5 py-0.2 rounded text-[9px] font-extrabold">🏠 OWN</span>`; const thumb = it.image ? `<button type="button" onclick="openAdminItemPreview('${chkKey}')" class="w-10 h-10 rounded-lg overflow-hidden border border-pink-200 shrink-0 bg-white"><img src="${escapeHtml(it.image)}" class="w-full h-full object-cover object-top"></button>` : `<div class="w-10 h-10 rounded-lg border bg-gray-100 flex items-center justify-center text-[9px] text-gray-400 shrink-0">ပုံမရှိ</div>`; return ` <div class="flex items-center gap-2 px-2 py-1.5 rounded-lg border ${isChecked ? 'bg-emerald-50 border-emerald-300' : 'bg-gray-50 border-gray-200'}"> <input type="checkbox" ${isChecked ? 'checked' : ''} onchange="togglePackingCheck('${chkKey}')" class="w-4 h-4 accent-emerald-600 shrink-0"> ${thumb} <div class="flex-1 min-w-0"> <div class="flex items-center gap-1 flex-wrap"> <span class="font-extrabold text-[11px] truncate ${isChecked ? 'line-through text-gray-400' : 'text-gray-900'}">${idx + 1}. ${escapeHtml(it.name)}</span> ${shopTag} </div> <div class="flex flex-wrap items-center gap-1 text-[9px] font-extrabold mt-0.5"> <span class="bg-purple-100 text-purple-800 px-1 rounded">🎨 ${escapeHtml(it.colorName || '-')}</span> ${it.size && it.size !== 'အသက်မလို' ? `<span class="bg-pink-100 text-pink-800 px-1 rounded">📏 ${escapeHtml(it.size)}</span>` : ''} <span class="bg-gray-900 text-white px-1.5 rounded">x${it.qty}</span> </div> </div> </div> `; }).join(''); const pickupOpts = `<option value="">-- Pickup ဝန်ထမ်း --</option>` + riders.map(r => `<option value="${escapeHtml(r.id)}" ${o.pickupRiderId === r.id ? 'selected' : ''}>${escapeHtml(r.id)} - ${escapeHtml(r.name)}</option>`).join(''); const delivOpts = `<option value="">-- Delivery ဝန်ထမ်း --</option>` + riders.map(r => `<option value="${escapeHtml(r.id)}" ${o.riderId === r.id ? 'selected' : ''}>${escapeHtml(r.id)} - ${escapeHtml(r.name)}</option>`).join(''); const pickupCompactHtml = hasPartner ? ` <div class="flex flex-wrap items-center gap-1.5 bg-purple-50/80 border border-purple-200 rounded-lg px-2 py-1.5"> <span class="text-[10px] font-extrabold text-purple-900">📦 Pickup:</span> <select onchange="adminAssignPickupRider('${o.orderId}', this)" class="flex-1 min-w-[130px] border border-purple-300 rounded-md px-2 py-1 text-[11px] font-bold bg-white">${pickupOpts}</select> <button type="button" onclick="adminForcePickupStatus('${o.orderId}', 'ဆိုင်မှ ပစ္စည်းကောက်ပြီးပြီ')" class="${adminPickupConfirmed ? 'bg-emerald-100 text-emerald-800 border border-emerald-300' : 'bg-emerald-600 text-white'} text-[10px] font-extrabold px-2 py-1 rounded-md">${adminPickupConfirmed ? '✅ ကောက်ပြီး' : '✅ ကောက်ပြီးပို့'}</button> </div> ` : ''; return ` <div class="rounded-2xl border-2 ${cardBorder} p-2.5 sm:p-3 shadow-sm space-y-2"> ${buildAdminOrderProcessSteps(o, hasPartner)} ${cancelReqBanner} ${rejectBadge} <div class="flex flex-wrap justify-between items-center gap-1 text-xs"> <div class="flex flex-wrap items-center gap-1.5"> <span class="font-extrabold text-gray-900">🧾 ${escapeHtml(o.orderId)}</span> <span class="text-[10px] text-gray-500">⏰ ${escapeHtml(o.dateTime)}</span> ${isShopPacked ? `<span class="bg-blue-600 text-white text-[9px] font-extrabold px-2 py-0.5 rounded-full">📦 ဆိုင်ထုပ်ပိုးပြီး</span>` : ''} </div> <span class="${isCodWait ? 'bg-emerald-600 animate-pulse' : 'bg-pink-600'} text-white text-[10px] font-extrabold px-2 py-0.5 rounded-full">${escapeHtml(o.status)}</span> </div> <div class="text-[11px] flex flex-wrap items-center justify-between gap-1 bg-gray-50 rounded-lg px-2.5 py-1.5 border border-gray-100"> <span class="font-extrabold text-gray-900">👤 ${escapeHtml(o.name)} (<a href="tel:${escapeHtml(o.phone)}" class="text-blue-700 underline">${escapeHtml(o.phone)}</a>) — <span class="font-normal text-gray-600">📍 ${escapeHtml(o.address)}</span></span> <span class="font-extrabold text-emerald-700 shrink-0">💰 ${Number(o.grandTotal || 0).toLocaleString()} Ks</span> </div> <div class="space-y-1">${itemsHtml}</div> ${pickupCompactHtml} <div class="flex flex-wrap items-center gap-1.5 bg-blue-50/80 border border-blue-200 rounded-lg px-2 py-1.5"> <span class="text-[10px] font-extrabold text-blue-900">🚚 Delivery:</span> <select onchange="adminAssignDeliveryRider('${o.orderId}', this)" class="flex-1 min-w-[130px] border border-blue-300 rounded-md px-2 py-1 text-[11px] font-bold bg-white">${delivOpts}</select> <button type="button" onclick="adminEditOrderMap('${o.orderId}', '${escapeHtml(o.mapLocation || '')}')" class="bg-white border border-blue-300 text-blue-700 text-[10px] font-extrabold px-2 py-1 rounded-md">📍 Map</button> <button type="button" onclick="adminConfirmCancel('${o.orderId}', ${hasPartner}, this)" class="bg-red-50 border border-red-200 text-red-700 text-[10px] font-extrabold px-2 py-1 rounded-md">❌ Cancel</button> <button type="button" onclick="adminMarkCodFinished('${o.orderId}', this)" class="${isCodWait ? 'bg-emerald-600 ring-2 ring-emerald-300 animate-pulse' : 'bg-gray-900'} text-white text-[10px] font-extrabold px-2.5 py-1 rounded-md">✅ COD Confirm</button> </div> </div> `; }).join(''); } // ---- TAB 2: RESTOCK REQUESTS ---- const rsEl = document.getElementById('adm-restocks-list'); if (restocks.length === 0) { rsEl.innerHTML = `<div class="bg-white rounded-2xl border p-8 text-center text-xs text-gray-400">✅ စစ်ဆေးရန် ကျန်ရှိသော Stock ထပ်တိုး စာရင်း မရှိပါ</div>`; } else { rsEl.innerHTML = restocks.map((rs, idx) => { const imgs = getRestockImagesArray(rs); const fIds = Array.isArray(rs.fileIds) ? rs.fileIds : []; const thumbsHtml = imgs.length > 0 ? `<div class="flex flex-wrap gap-2">${imgs.map((imgUrl, iIdx) => { const pvKey = `rst_${rs.requestId}_${idx}_${iIdx}`; const fId = fIds[iIdx] || extractDriveIdClient(imgUrl); const cachedData = fId && window.__b64ImgCache[fId]; const displaySrc = cachedData ? cachedData.dataUrl : getSizedImageUrl(imgUrl, 400); window.__adminPreviewMap[pvKey] = { name: `${rs.productName} (ပုံ ${iIdx + 1})`, shopId: rs.shopId, colorName: rs.color || rs.category, size: rs.size, qty: rs.qty, price: rs.price || 0, image: imgUrl, fileId: fId, allowDownload: true }; return `<button type="button" onclick="openAdminItemPreview('${pvKey}')" class="relative w-20 h-20 rounded-xl overflow-hidden border-2 ${iIdx === 0 ? 'border-amber-400' : 'border-gray-200'} bg-gray-50 shrink-0"><img src="${escapeHtml(displaySrc)}" onerror="loadDriveImageFallback(this, '${escapeHtml(fId)}')" class="w-full h-full object-cover"></button>`; }).join('')}</div>` : `<div class="w-20 h-20 rounded-xl border border-dashed bg-gray-100 flex items-center justify-center text-[10px] text-gray-400">ပုံမရှိ</div>`; return ` <div class="bg-white rounded-2xl border-2 border-amber-300 p-3.5 shadow-sm space-y-2.5"> <div class="flex flex-wrap justify-between items-center gap-1.5"> <span class="bg-amber-100 text-amber-900 px-2.5 py-0.5 rounded-full text-[10px] font-extrabold">🏪 ${escapeHtml(rs.shopId)} — ${escapeHtml(rs.shopName)}</span> <span class="text-[10px] text-gray-500">⏰ ${escapeHtml(rs.dateTime)}</span> </div> <p class="font-extrabold text-sm text-gray-900">${escapeHtml(rs.productName)} <span class="text-emerald-700 text-xs">(+${rs.qty} ခု | ${Number(rs.price || 0).toLocaleString()} Ks)</span></p> ${thumbsHtml} <div class="flex flex-wrap gap-2 pt-2 border-t border-gray-100"> <button type="button" onclick="openRestockEditModal('${escapeHtml(rs.requestId)}')" class="bg-blue-600 text-white font-extrabold px-3 py-2 rounded-xl text-xs">✏️ Edit ပြင်မည်</button> <button type="button" onclick="adminApproveRestock('${escapeHtml(rs.requestId)}', this)" class="flex-1 sm:flex-none bg-emerald-600 text-white font-extrabold px-4 py-2 rounded-xl text-xs">✅ Approve</button> <button type="button" onclick="openRejectRestockModal('${escapeHtml(rs.requestId)}')" class="bg-red-50 text-red-700 border border-red-200 font-extrabold px-3 py-2 rounded-xl text-xs">❌ ပယ်ချ</button> </div> </div> `; }).join(''); } // ---- TAB 3: RETURNS ---- const retEl = document.getElementById('adm-returns-list'); if (returns.length === 0) { retEl.innerHTML = `<div class="bg-white rounded-2xl border p-8 text-center text-xs text-gray-400">✅ လက်ရှိ Return / Cancel Return စာရင်း မရှိပါ</div>`; } else { retEl.innerHTML = returns.map(r => { const ri = r.returnInfo || {}; const shopRets = ri.shopReturns || {}; const shopRetKeys = Object.keys(shopRets); const isHubGot = ri.status !== 'rider_returning_to_hub'; const isClosed = ri.status === 'closed'; const isConfirmedToShop = !!ri.adminConfirmedToShop; const retRiderOpts = `<option value="">-- ပြန်အပ်မည့် ဝန်ထမ်း --</option>` + riders.map(rd => `<option value="${escapeHtml(rd.id)}" ${ri.returnRiderId === rd.id ? 'selected' : ''}>${escapeHtml(rd.id)} — ${escapeHtml(rd.name)}</option>`).join(''); const shopRetStatusHtml = shopRetKeys.map(sid => { const sr = shopRets[sid]; return `<div class="flex justify-between items-center text-xs bg-white border rounded-lg px-2.5 py-1.5"><span class="font-extrabold">🏪 ${escapeHtml(sid)}</span><span class="bg-gray-100 text-gray-800 px-2 py-0.5 rounded-full text-[10px] font-extrabold">${escapeHtml(sr.status)}</span></div>`; }).join(''); const shopConfirmBanner = (shopRetKeys.length > 0 && !isClosed && !isConfirmedToShop) ? `<div class="bg-amber-100 border border-amber-400 rounded-xl p-2 flex justify-between items-center gap-2"><span class="text-xs font-extrabold text-amber-950">🔒 ဆိုင်ထံ Confirm မပို့ရသေး</span><button type="button" onclick="adminConfirmReturnNotifyShop('${r.orderId}', this)" class="bg-red-600 text-white font-extrabold px-3 py-1 rounded-lg text-xs">🔔 Return Confirm</button></div>` : ''; return ` <div class="rounded-2xl border-2 ${isClosed ? 'border-gray-200 bg-white opacity-80' : 'border-red-300 bg-red-50/30'} p-3.5 space-y-2 shadow-sm"> ${shopConfirmBanner} <div class="flex justify-between items-center text-xs"> <span class="font-extrabold text-gray-900">🔄 ${escapeHtml(r.orderId)} — ${escapeHtml(r.name)} (${escapeHtml(r.phone)})</span> <span class="${isClosed ? 'bg-gray-700' : 'bg-red-600'} text-white text-[10px] font-extrabold px-2 py-0.5 rounded-full">${isClosed ? '✅ Closed' : '🔄 Return'}</span> </div> <p class="text-xs font-bold text-red-700">❌ ${escapeHtml(ri.reason || 'COD ငြင်း')}</p> ${shopRetStatusHtml} ${!isHubGot ? `<button type="button" onclick="adminReceiveReturnHub('${r.orderId}', ${!!ri.hasOwn}, this)" class="bg-emerald-600 text-white font-extrabold px-3 py-1.5 rounded-xl text-xs">📦 Hub ပြန်လက်ခံပြီး</button>` : (shopRetKeys.length > 0 && !isClosed ? `<select onchange="adminAssignReturnRider('${r.orderId}', this)" class="w-full border border-orange-300 rounded-xl px-2.5 py-1.5 text-xs font-bold bg-white">${retRiderOpts}</select>` : '')} </div> `; }).join(''); } // ---- TAB 4: PAYOUTS ---- const payEl = document.getElementById('adm-payouts-list'); if (payouts.length === 0) { payEl.innerHTML = `<div class="bg-white rounded-2xl border p-8 text-center text-xs text-gray-400">✅ ရှင်းပေးရန်ကျန်သော 95% ဆိုင်ငွေစာရင်း မရှိသေးပါ</div>`; } else { const grouped = {}; payouts.forEach(p => { if (!grouped[p.shopId]) grouped[p.shopId] = { shopId: p.shopId, shopName: p.shopName, paymentAccount: p.paymentAccount, totalPayout: 0, list: [] }; grouped[p.shopId].totalPayout += Number(p.payout || 0); grouped[p.shopId].list.push(p); }); payEl.innerHTML = Object.values(grouped).map(g => ` <div class="bg-white rounded-2xl border-2 border-emerald-200 overflow-hidden shadow-sm"> <div class="bg-emerald-700 text-white p-3 flex flex-wrap justify-between items-center gap-2"> <div> <h4 class="font-extrabold text-sm">🏪 ${escapeHtml(g.shopId)} — ${escapeHtml(g.shopName)}</h4> <p class="text-[11px] text-emerald-100 font-bold">💳 ${escapeHtml(g.paymentAccount || 'မထည့်ရသေး')} ${g.paymentAccount ? `<button type="button" onclick="copyTextToClipboard('${escapeHtml(g.paymentAccount)}', '💳 Copy ပြီး!')" class="ml-1 bg-white/20 px-2 py-0.5 rounded text-[10px]">📋 Copy</button>` : ''}</p> </div> <p class="text-base font-extrabold">${g.totalPayout.toLocaleString()} Ks</p> </div> <div class="divide-y p-3 text-xs"> ${g.list.map(item => ` <div class="py-2 flex flex-wrap justify-between items-center gap-2"> <div> <p class="font-extrabold text-gray-900">🧾 ${escapeHtml(item.orderId)} — ${escapeHtml(item.customerName)}</p> <p class="text-[11px] text-gray-500">${escapeHtml(item.deliveredAt)}</p> </div> <div class="flex items-center gap-2"> <span class="font-extrabold text-emerald-700">${Number(item.payout).toLocaleString()} Ks</span> <button type="button" onclick="adminSettleShopOrder('${item.orderId}', '${item.shopId}', this)" class="bg-emerald-600 text-white font-extrabold px-3 py-1 rounded-xl text-[11px]">💸 ရှင်းပြီး</button> </div> </div> `).join('')} </div> </div> `).join(''); } renderAdminPayoutHistory(); // ---- TAB 6: SHOPS LIST WITH REQUEST APPROVAL ---- document.getElementById('adm-shops-list').innerHTML = shops.length === 0 ? `<p class="text-gray-400 py-3">ချိတ်ဆက်ဆိုင် မထည့်ရသေးပါ။</p>` : shops.map(s => { const isReq = s.approvalStatus === 'Pending'; const isApp = s.approvalStatus === 'Approved'; const appBadge = isReq ? `<span class="bg-red-600 text-white px-2 py-0.5 rounded-full text-[10px] font-extrabold animate-pulse">🔔 Request (အတည်ပြုရန်)</span>` : (isApp ? `<span class="bg-emerald-100 text-emerald-800 px-2 py-0.5 rounded-full text-[10px] font-extrabold">✅ Approved</span>` : `<span class="bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full text-[10px] font-bold">⏳ မတင်ရသေး</span>`); return ` <div class="py-2.5 flex flex-wrap justify-between items-center gap-2 ${isReq ? 'bg-amber-50/80 px-2.5 rounded-xl border border-amber-300 my-1' : ''}"> <div> <p class="font-extrabold text-gray-900">${escapeHtml(s.id)} — ${escapeHtml(s.name)} ${appBadge}</p> ${s.businessName ? `<p class="text-[11px] font-bold text-amber-900">🏢 လုပ်ငန်းအမည်: ${escapeHtml(s.businessName)}</p>` : ''} <p class="text-[11px] text-gray-500">🔑 PIN: ${escapeHtml(s.pin)} | ${s.commissionRate}% | 📞 ${escapeHtml(s.phone || '-')} | 💳 ${escapeHtml(s.paymentAccount || '-')}</p> </div> <div class="flex flex-wrap gap-1.5"> ${isReq ? `<button type="button" onclick="adminApproveShopRequest('${escapeHtml(s.id)}', this)" class="bg-emerald-600 hover:bg-emerald-700 text-white font-extrabold px-3 py-1.5 rounded-lg text-xs shadow-sm animate-pulse">✅ Approve ပေးမည်</button>` : ''} <button type="button" onclick="editShopAdmin('${escapeHtml(s.id)}')" class="bg-blue-100 text-blue-700 font-bold px-2.5 py-1 rounded-lg">✏️ ပြင်</button> <button type="button" onclick="deleteShopAdmin('${escapeHtml(s.id)}')" class="bg-red-100 text-red-700 font-bold px-2.5 py-1 rounded-lg">🗑️</button> </div> </div> `; }).join(''); // ---- TAB 7: RIDERS ---- document.getElementById('adm-riders-stats').innerHTML = (d.riderStats || []).map(rs => ` <div class="bg-blue-50/70 border border-blue-200 rounded-xl p-2.5 text-xs"> <p class="font-extrabold text-gray-900">${escapeHtml(rs.riderId)} — ${escapeHtml(rs.riderName)}</p> <p class="text-[11px] text-gray-600">ပို့ရန်: <b>${rs.pendingCount}</b> | ယနေ့ပြီး: <b>${rs.todayDeliveredCount}</b></p> <p class="text-xs font-extrabold text-emerald-700">💰 ယနေ့ COD: ${Number(rs.todayCodTotal || 0).toLocaleString()} Ks</p> </div> `).join(''); document.getElementById('adm-riders-list').innerHTML = riders.map(r => ` <div class="py-2 flex justify-between items-center gap-2"> <div> <span class="font-extrabold text-gray-900">${escapeHtml(r.id)} — ${escapeHtml(r.name)}</span> <span class="text-[11px] text-gray-500 ml-2">📞 ${escapeHtml(r.phone || '-')} | 🔑 PIN: ${escapeHtml(r.pin)}</span> </div> <div class="flex gap-1.5"> <button type="button" onclick="editRiderAdmin('${escapeHtml(r.id)}')" class="bg-blue-100 text-blue-700 font-bold px-2.5 py-1 rounded-lg">✏️</button> <button type="button" onclick="deleteRiderAdmin('${escapeHtml(r.id)}')" class="bg-red-100 text-red-700 font-bold px-2.5 py-1 rounded-lg">🗑️</button> </div> </div> `).join(''); } async function adminApproveShopRequest(shopId, btnEl) { if (!confirm(`ဆိုင် (${shopId}) ၏ သဘောတူညီချက်ကို အတည်ပြုပြီး Shop App အသုံးပြုခွင့် ပေးပါမည်လား?`)) return; if (btnEl) { btnEl.disabled = true; btnEl.innerText = '⏳...'; } await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: 'adminApproveShop', shopId }) }); showBannerNoti(`✅ ဆိုင် (${shopId}) အတည်ပြုပြီး`, 'Shop App ကို ယခုစတင်အသုံးပြုနိုင်ပါပြီ။'); setTimeout(() => loadAdminDashboard(false), 900); } async function adminConfirmCancel(orderId, hasPartner, btnEl) { const reason = prompt(`အော်ဒါ #${orderId} ကို Cancel Confirm လုပ်မည်လား?\n\nအကြောင်းရင်း (ရှိပါက ထည့်ရေးနိုင်သည်):`, ''); if (reason === null) return; if (btnEl) { btnEl.disabled = true; btnEl.innerText = '⏳...'; } await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: 'adminConfirmCancelOrder', orderId, reason: (reason || '').trim() }) }); setTimeout(() => { loadAdminDashboard(false); loadProducts(false); }, 1000); } async function adminConfirmReturnNotifyShop(orderId, btnEl) { if (!confirm(`Return အော်ဒါ #${orderId} ကို Confirm လုပ်ပြီး ဆိုင် App ထံ ပို့ပါမည်လား?`)) return; if (btnEl) { btnEl.disabled = true; btnEl.innerText = '⏳...'; } await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: 'adminConfirmReturnToShop', orderId }) }); setTimeout(() => loadAdminDashboard(false), 900); } async function adminApproveRestock(requestId, btnEl) { if (!confirm(`Stock ထပ်တိုး Request (${requestId}) ကို Approve လုပ်ပြီး ဝယ်သူ App ထဲ ထည့်ပါမည်လား?`)) return; if (btnEl) { btnEl.disabled = true; btnEl.innerText = '⏳...'; } await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: 'adminApproveRestock', requestId }) }); setTimeout(() => { loadAdminDashboard(false); loadProducts(true); }, 1400); } function editMasterSheetLink() { const cur = (adminDataCache && adminDataCache.sheetUrl) || localStorage.getItem('mt_master_sheet_url') || ''; const pasted = prompt('သင့် Google Sheet Link ကို ထည့်သွင်းပါ:', cur); if (pasted !== null && pasted.trim()) { try { localStorage.setItem('mt_master_sheet_url', pasted.trim()); } catch (e) {} alert('✅ Google Sheet Link သိမ်းဆည်းပြီးပါပြီ!'); } } function openGoogleSheetForStock(catName) { const catUrls = (adminDataCache && adminDataCache.categorySheetUrls) ? adminDataCache.categorySheetUrls : {}; let targetUrl = (catName && catUrls[catName]) ? catUrls[catName] : ((adminDataCache && adminDataCache.sheetUrl) || localStorage.getItem('mt_master_sheet_url') || ''); if (!targetUrl) { const pasted = prompt('Google Sheet Link ထည့်ပေးပါ:', ''); if (!pasted || !pasted.trim()) return; targetUrl = pasted.trim(); try { localStorage.setItem('mt_master_sheet_url', targetUrl); } catch (e) {} } window.open(targetUrl, '_blank', 'noopener'); } async function syncStockFromSheet(btnEl) { const orig = btnEl ? btnEl.innerText : ''; if (btnEl) { btnEl.disabled = true; btnEl.innerText = '⏳ Sync...'; } await loadProducts(true); if (btnEl) { btnEl.disabled = false; btnEl.innerText = '✅ Sync ပြီး'; setTimeout(() => { btnEl.innerText = orig || '🔄 Sheet မှ Sync ဆွဲမည်'; }, 2000); } } function renderAdminStockPanel() { const box = document.getElementById('adm-stock-list'); if (!box) return; const shopF = document.getElementById('adm-stock-shop-filter')?.value || 'ALL'; const catF = document.getElementById('adm-stock-cat-filter')?.value || 'ALL'; const q = (document.getElementById('adm-stock-search')?.value || '').trim().toLowerCase(); const list = allProducts.filter(p => { if (shopF !== 'ALL' && p.shopId !== shopF) return false; if (catF !== 'ALL' && p.category !== catF) return false; if (q && !p.name.toLowerCase().includes(q) && !p.category.toLowerCase().includes(q)) return false; return true; }); if (list.length === 0) { box.innerHTML = `<p class="text-xs text-gray-400 py-8 text-center bg-white rounded-2xl border">ပစ္စည်း မတွေ့ရှိပါ</p>`; return; } box.innerHTML = list.map(p => { const isPartner = p.shopId !== 'OWN'; const needsAge = AGE_REQUIRED_CATS.includes(p.category); const imgUrl = getSizedImageUrl((p.colors[0] && p.colors[0].image) ? p.colors[0].image : './icon.png?v=3', 400); const isTotalLow = p.totalStock <= 5; let sizesHtml = !needsAge ? `<div class="flex items-center justify-between bg-gray-50 border rounded-xl px-3 py-1.5 text-xs"><span class="font-bold">📦 Stock</span><span class="font-extrabold ${p.totalStock <= 5 ? 'text-red-600' : 'text-emerald-700'}">${p.totalStock} ခု</span></div>` : SIZE_LABELS.map((sz, i) => (p.prices[i] <= 0 && p.stocks[i] <= 0) ? '' : `<div class="flex items-center justify-between bg-gray-50 border rounded-xl px-2.5 py-1 text-xs"><span class="font-bold">${escapeHtml(sz)}</span><span class="font-extrabold ${(p.stocks[i] || 0) <= 5 ? 'text-red-600' : 'text-emerald-700'}">${p.stocks[i] || 0} ခု</span></div>`).join(''); return ` <div class="bg-white rounded-2xl border ${isTotalLow ? 'border-red-300' : 'border-gray-200'} p-3 shadow-sm space-y-2"> <div class="flex items-center justify-between gap-2"> <div class="flex items-center gap-2 min-w-0 flex-1"> <img src="${escapeHtml(imgUrl)}" class="w-11 h-11 rounded-xl object-cover border shrink-0"> <div class="min-w-0 flex-1"> <span class="${isPartner ? 'bg-amber-100 text-amber-900' : 'bg-blue-100 text-blue-800'} text-[10px] font-extrabold px-1.5 py-0.5 rounded">${isPartner ? '🏪 ' + escapeHtml(p.shopId) : '🏠 OWN'}</span> <span class="text-[10px] text-gray-500 font-bold ml-1">${escapeHtml(p.category)}</span> <p class="font-extrabold text-xs text-gray-900 truncate mt-0.5">${escapeHtml(p.name)}</p> </div> </div> <button type="button" onclick="openGoogleSheetForStock('${escapeHtml(p.category)}')" class="bg-emerald-50 text-emerald-800 border border-emerald-300 font-extrabold text-[11px] px-2.5 py-1.5 rounded-xl shrink-0">📗 Sheet</button> </div> <div class="grid grid-cols-2 sm:grid-cols-3 gap-1.5">${sizesHtml}</div> </div> `; }).join(''); } async function adminAssignPickupRider(orderId, selEl) { const riderId = selEl.value; const riderName = riderId ? selEl.options[selEl.selectedIndex].text.split(' - ')[1] || '' : ''; await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: 'assignPickupRider', orderId, riderId, riderName }) }); setTimeout(() => loadAdminDashboard(false), 800); } async function adminForcePickupStatus(orderId, pickupStatus) { await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: 'updatePickupStatus', orderId, pickupStatus, riderName: 'Admin', byAdmin: true }) }); setTimeout(() => loadAdminDashboard(false), 800); } async function adminAssignDeliveryRider(orderId, selEl) { const riderId = selEl.value; const riderName = riderId ? selEl.options[selEl.selectedIndex].text.split(' - ')[1] || '' : ''; await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: 'assignRider', orderId, riderId, riderName }) }); setTimeout(() => loadAdminDashboard(false), 800); } async function adminEditOrderMap(orderId, currentMap) { const val = prompt(`အော်ဒါ #${orderId} အတွက် GPS (lat,lng) သို့မဟုတ် Google Maps Link ထည့်ပါ:`, currentMap || ''); if (val === null) return; await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: 'updateOrderMap', orderId, mapLocation: val.trim() }) }); setTimeout(() => loadAdminDashboard(false), 800); } async function adminMarkCodFinished(orderId, btnEl) { if (!confirm(`အော်ဒါ #${orderId} COD ငွေလက်ခံပြီး (COD Confirm) အတည်ပြုပါမည်လား?`)) return; if (btnEl) { btnEl.disabled = true; btnEl.innerText = '⏳...'; } await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: 'markDelivered', orderId }) }); setTimeout(() => loadAdminDashboard(false), 900); } async function adminReceiveReturnHub(orderId, hasOwn, btnEl) { if (btnEl) { btnEl.disabled = true; btnEl.innerText = '⏳...'; } await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: 'adminReceiveReturnAtHub', orderId, restockOwn: hasOwn }) }); setTimeout(() => { loadAdminDashboard(false); if (hasOwn) loadProducts(false); }, 900); } async function adminAssignReturnRider(orderId, selEl) { const riderId = selEl.value; const riderName = riderId ? selEl.options[selEl.selectedIndex].text.split(' — ')[1] || '' : ''; if (!riderId) return; await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: 'assignReturnRider', orderId, riderId, riderName }) }); setTimeout(() => loadAdminDashboard(false), 800); } async function adminSettleShopOrder(orderId, shopId, btnEl) { if (!confirm(`အော်ဒါ #${orderId} အတွက် ဆိုင် (${shopId}) သို့ 95% ရှင်းပြီးကြောင်း မှတ်တမ်းတင်ပါမည်လား?`)) return; if (btnEl) { btnEl.disabled = true; btnEl.innerText = '⏳...'; } await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: 'markShopOrderSettled', orderId, shopId }) }); setTimeout(() => loadAdminDashboard(false), 900); } function resetShopForm() { ['sf-id', 'sf-name', 'sf-phone', 'sf-pin', 'sf-address', 'sf-map', 'sf-pay'].forEach(id => { document.getElementById(id).value = ''; }); document.getElementById('sf-comm').value = '5'; } function editShopAdmin(shopId) { const s = (adminDataCache?.shops || []).find(x => x.id === shopId); if (!s) return; document.getElementById('sf-id').value = s.id; document.getElementById('sf-name').value = s.name; document.getElementById('sf-phone').value = s.phone; document.getElementById('sf-pin').value = s.pin; document.getElementById('sf-comm').value = s.commissionRate; document.getElementById('sf-address').value = s.address; document.getElementById('sf-map').value = s.mapLocation; document.getElementById('sf-pay').value = s.paymentAccount; document.getElementById('sf-name').focus(); } async function saveShopAdmin(e) { e.preventDefault(); const btn = document.getElementById('btn-save-shop'); btn.disabled = true; btn.innerText = '⏳ သိမ်းနေ...'; await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: 'saveShop', shopId: document.getElementById('sf-id').value.trim(), name: document.getElementById('sf-name').value.trim(), phone: document.getElementById('sf-phone').value.trim(), pin: document.getElementById('sf-pin').value.trim(), commissionRate: document.getElementById('sf-comm').value, address: document.getElementById('sf-address').value.trim(), mapLocation: document.getElementById('sf-map').value.trim(), paymentAccount: document.getElementById('sf-pay').value.trim() }) }); resetShopForm(); btn.disabled = false; btn.innerText = '💾 ဆိုင်သိမ်းမည်'; setTimeout(() => loadAdminDashboard(false), 900); } async function deleteShopAdmin(shopId) { if (!confirm(`ဆိုင် (${shopId}) ကို ဖျက်မည်မှာ သေချာပါသလား?`)) return; await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: 'deleteShop', shopId }) }); setTimeout(() => loadAdminDashboard(false), 800); } function resetRiderForm() { ['rf-id', 'rf-name', 'rf-phone', 'rf-pin'].forEach(id => { document.getElementById(id).value = ''; }); } function editRiderAdmin(riderId) { const r = (adminDataCache?.riders || []).find(x => x.id === riderId); if (!r) return; document.getElementById('rf-id').value = r.id; document.getElementById('rf-name').value = r.name; document.getElementById('rf-phone').value = r.phone; document.getElementById('rf-pin').value = r.pin; document.getElementById('rf-name').focus(); } async function saveRiderAdmin(e) { e.preventDefault(); await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: 'saveRider', riderId: document.getElementById('rf-id').value.trim(), name: document.getElementById('rf-name').value.trim(), phone: document.getElementById('rf-phone').value.trim(), pin: document.getElementById('rf-pin').value.trim() }) }); resetRiderForm(); setTimeout(() => loadAdminDashboard(false), 900); } async function deleteRiderAdmin(riderId) { if (!confirm(`ဝန်ထမ်း (${riderId}) ကို ဖျက်မည်မှာ သေချာပါသလား?`)) return; await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: 'deleteRider', riderId }) }); setTimeout(() => loadAdminDashboard(false), 800); } async function sendBroadcastAdmin(e) { e.preventDefault(); let targetVal = 'all'; let targetLabel = '🛍️ ဝယ်သူအားလုံး'; if (currentNotiAudience === 'customer' && currentCustNotiMode === 'single') { const sel = document.getElementById('bc-cust-target'); if (!sel || !sel.value) { alert('⚠️ ပေးပို့မည့် ဝယ်သူကို ရွေးချယ်ပေးပါ။'); return; } targetVal = sel.value; targetLabel = sel.options[sel.selectedIndex].text; } else if (currentNotiAudience === 'rider') { const sel = document.getElementById('bc-rider-target'); targetVal = sel ? sel.value : 'all_riders'; targetLabel = sel && sel.selectedIndex >= 0 ? sel.options[sel.selectedIndex].text : '🚚 Delivery ဝန်ထမ်းအားလုံး'; } else if (currentNotiAudience === 'shop') { const sel = document.getElementById('bc-shop-target'); targetVal = sel ? sel.value : 'all_shops'; targetLabel = sel && sel.selectedIndex >= 0 ? sel.options[sel.selectedIndex].text : '🏪 ချိတ်ဆက်ဆိုင်အားလုံး'; } if (!confirm(`ဤ Notification ကို\n\n👉 ${targetLabel}\n\nထံသို့ ပေးပို့မည်မှာ သေချာပါသလား?`)) return; const btn = document.getElementById('btn-send-bc'); const prevBtnText = btn.innerText; btn.disabled = true; btn.innerText = '⏳ ပို့နေသည်...'; try { const res = await fetch(APPS_SCRIPT_URL, { method: 'POST', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: 'sendBroadcast', target: targetVal, title: document.getElementById('bc-title').value.trim(), message: document.getElementById('bc-msg').value.trim() }) }); const data = await res.json(); const r = (data && data.fcmResult) ? data.fcmResult : {}; document.getElementById('bc-title').value = ''; document.getElementById('bc-msg').value = ''; if (r.sent > 0) { alert(`✅ ${targetLabel} ထံ Notification ရောက်ရှိပြီးပါပြီ! (ဖုန်း ${r.sent} လုံး)`); } else { alert(`⚠️ Noti မရောက်ပါ!\n\nအဖြေ: ${JSON.stringify(r)}`); } } catch (err) { alert('⚠️ ပေးပို့ရာတွင် အင်တာနက်ချိတ်ဆက်မှု စစ်ဆေးပေးပါ။'); } btn.disabled = false; btn.innerText = prevBtnText; } async function setupCategorySheetsAdmin() { if (!confirm('Google Sheet Timezone ကို မြန်မာအချိန် (Asia/Yangon) ပြောင်းပြီး Sheet အသစ်များ၊ Customers Sheet နှင့် နံနက် ၈:၀၀ ဆိုင် Noti Trigger တည်ဆောက်မည်လား?')) return; await fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: 'setupCategorySheets' }) }); alert('✅ Sheet အသစ်များနှင့် Trigger တည်ဆောက်ပြီးပါပြီ!'); setTimeout(() => { loadAdminDashboard(false); loadProducts(true); }, 1000); } function copyTextToClipboard(text, msg) { if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(text).then(() => alert(msg || '✅ Copy ပြီးပါပြီ!')); } else { const ta = document.createElement('textarea'); ta.value = text; document.body.appendChild(ta); ta.select(); document.execCommand('copy'); document.body.removeChild(ta); alert(msg || '✅ Copy ပြီးပါပြီ!'); } } // ==================== INITIALIZATION ==================== function init() { if (APP_ROLE === 'admin') { document.getElementById('admin-view').classList.remove('hidden'); if (!isStandaloneApp()) { document.getElementById('btn-admin-install-login')?.classList.remove('hidden'); document.getElementById('btn-admin-install')?.classList.remove('hidden'); } updateAdminClock(); setInterval(updateAdminClock, 1000); if (localStorage.getItem('mt_admin_authed') === '1') { showAdminDashboard(); } setInterval(() => { if (!document.getElementById('admin-dashboard').classList.contains('hidden')) { loadAdminDashboard(true); } }, 25000); } else { document.getElementById('customer-view').classList.remove('hidden'); if (!isStandaloneApp() && isIOSDevice()) { document.getElementById('btn-install-app').classList.remove('hidden'); } try { history.replaceState({ mtHome: true }, ''); } catch (e) {} renderCategoryBar(); loadSavedCart(); loadProductsFromCacheInstant(); loadProducts(false); refreshCustomerOrders(false); if (!sessionStorage.getItem('mt_visit_logged')) { sessionStorage.setItem('mt_visit_logged', '1'); fetch(APPS_SCRIPT_URL, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: 'visit', device: isIOSDevice() ? 'iPhone/iPad' : (/Android/i.test(navigator.userAgent) ? 'Android' : 'Desktop'), mode: isStandaloneApp() ? 'App' : 'Browser' }) }).catch(() => {}); } setTimeout(() => { if ('Notification' in window && Notification.permission === 'granted') { initFirebasePush('customer', false); } }, 1500); setInterval(() => refreshCustomerOrders(false), 25000); setInterval(() => updateCancelCountdowns(), 1000); } } init(); </script> </body> </html>