/* CANVAS TO IMAGE FILE */ function canvasToBlob(canvas){ return new Promise((resolve,reject)=>{ canvas.toBlob(blob=>{ if(blob) resolve(blob); else reject(new Error('Could not create sticker design image.')); },'image/jpeg',0.92); }); } /* UPLOAD PHOTO */ async function uploadSticker(file,prefix){ const extension=file.type==='image/png'?'png': file.type==='image/webp'?'webp':'jpg'; const path=`${prefix}/${Date.now()}-${crypto.randomUUID()}.${extension}`; const {error}=await supabase.storage .from('tycf-sticker-photos') .upload(path,file,{contentType:file.type,upsert:false}); if(error) throw error; return path; } /* UPI QR */ function showPaymentQR(amount){ const qrBox=$('paymentQr'); qrBox.innerHTML=''; qrBox.style.display='block'; const upiLink=`upi://pay?pa=${encodeURIComponent(UPI_ID)}&pn=${encodeURIComponent('TYCF Food Donation')}&am=${Number(amount).toFixed(2)}&cu=INR&tn=${encodeURIComponent('TYCF Food Donation')}`; if(typeof QRCode==='undefined'){ $('qrMsg').textContent='QR library could not load.'; return; } new QRCode(qrBox,{ text:upiLink, width:280, height:280, correctLevel:QRCode.CorrectLevel.H }); $('qrMsg').textContent='Scan this QR using your UPI app. Verify recipient before paying.'; $('paymentAmount').textContent='Donation Amount: '+format(amount); $('paymentReference').textContent='UPI ID: '+UPI_ID; } /* BOOKING SUBMISSION */ $('bookingForm').addEventListener('submit',async e=>{ e.preventDefault(); const button=$('submitBtn'); const message=$('formMsg'); const {items,total}=calculateTotal(); message.textContent=''; if(!items.length){ message.textContent='Please select at least one package.'; return; } const customerName=$('customerName').value.trim(); const mobile=$('mobile').value.trim(); const donationDate=$('donationDate').value; if(!/^[0-9+\-\s]{10,15}$/.test(mobile)){ message.textContent='Please enter a valid mobile number.'; return; } if(!donationDate){ message.textContent='Please select donation date.'; return; } if(!$('consent').checked){ message.textContent='Please accept the consent checkbox.'; return; } button.disabled=true; button.textContent='Submitting...'; try{ let photoPath=null; let designPath=null; const photoFile=$('stickerPhoto').files[0]; if(photoFile){ photoPath=await uploadSticker(photoFile,'customer-photos'); } if(stickerImage){ const blob=await canvasToBlob(canvas); const designFile=new File( [blob], 'tycf-sticker-design.jpg', {type:'image/jpeg'} ); designPath=await uploadSticker(designFile,'sticker-designs'); } const packageNames=items .map(item=>`${item.name} x ${item.quantity}`) .join(', '); const orderData={ customer_name:customerName, customer_mobile:mobile, occasion:$('occasion').value, donation_date:donationDate, package_name:packageNames, package_price:total, sticker_name:$('stickerName').value.trim(), customer_message:[ $('customerMessage').value.trim(), $('bestWishesFrom').value.trim() ].filter(Boolean).join(' | '), sticker_photo_path:photoPath, sticker_design_path:designPath, payment_status:'Pending', status:'Received' }; const {error}=await supabase .from('tycf_orders') .insert([orderData]); if(error) throw error; message.textContent='Booking submitted successfully! Please complete UPI payment.'; showPaymentQR(total); $('payment').scrollIntoView({behavior:'smooth'}); }catch(error){ console.error('Booking error:',error); message.textContent='Booking failed: '+(error.message||'Please try again.'); }finally{ button.disabled=false; button.textContent='Submit Donation Request'; } }); /* INITIAL SETUP */ function setMinimumDate(){ const today=new Date(); const localDate=new Date( today.getTime()-today.getTimezoneOffset()*60000 ).toISOString().split('T')[0]; $('donationDate').min=localDate; } setMinimumDate(); updatePackagePrices(); loadPrices(); /* INSTALL APP */ let deferredInstallPrompt=null; const installButton=$('installAppBtn'); const installHelp=$('installAppHelp'); window.addEventListener('beforeinstallprompt',e=>{ e.preventDefault(); deferredInstallPrompt=e; }); installButton.addEventListener('click',async()=>{ if(deferredInstallPrompt){ deferredInstallPrompt.prompt(); const result=await deferredInstallPrompt.userChoice; installHelp.textContent=result.outcome==='accepted' ?'TYCF app installation started.' :'You can install the app later from your browser menu.'; deferredInstallPrompt=null; }else{ installHelp.textContent='Open browser menu and select Add to Home screen or Install app.'; } }); window.addEventListener('appinstalled',()=>{ installHelp.textContent='TYCF app installed successfully.'; installButton.hidden=true; }); /* SERVICE WORKER */ if('serviceWorker' in navigator){ window.addEventListener('load',()=>{ navigator.serviceWorker.register('/sw.js') .then(()=>console.log('Service Worker registered.')) .catch(error=>console.error('Service Worker error:',error)); }); }