import html
import json
import math
from datetime import timedelta
from core import *
import gateway
import sms

def e(value):
    return html.escape(str(value if value is not None else ''),quote=True)

def url(r,path,**params):
    return e(r.url(path,**params))

def page(r,title,body,cls=''):
    return f"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>{e(title)} · Astha Pharmacy Soft</title><link rel="stylesheet" href="{url(r,'/static/style.css')}">
<script defer src="{url(r,'/static/app.js')}"></script></head><body class="{e(cls)}">{body}</body></html>"""

def brand(r,admin=False):
    return f"""<a class="brand" href="{url(r,'/admin' if admin else '/')}"><span class="mark" aria-hidden="true">✚</span>
<span><b>{'Astha Pharmacy' if admin else e(r.setting.get('store','Astha Pharmacy'))}</b><small>{'SOFT BY ZEEKODES' if admin else 'POWERED BY ZEEKODES'}</small></span></a>"""

def notice(r):
    f=r.consume_flash()
    return f'<div role="status" class="notice {e(f[1])}">{e(f[0])}</div>' if f else ''

def button(label,cls='primary'):
    return f'<button class="btn {cls}" type="submit">{e(label)}</button>'

def link(href,label,cls='secondary'):
    return f'<a class="btn {cls}" href="{href}">{e(label)}</a>'

def hidden(key,value):
    return f'<input type="hidden" name="{e(key)}" value="{e(value)}">'

def form(r,action,body,path=None,files=False,cls=''):
    encoding=' enctype="multipart/form-data"' if files else ''
    return f'<form method="post" action="{url(r,path or r.route)}" class="{cls}"{encoding}>{hidden("csrf",r.session["csrf"])}{hidden("action",action)}{body}</form>'

def inp(key,label,value='',kind='text',required=False,extra=''):
    return f'<label>{e(label)}<input name="{e(key)}" type="{e(kind)}" value="{e(value)}" {"required" if required else ""} {extra}></label>'

def textarea(key,label,value='',required=False):
    return f'<label>{e(label)}<textarea name="{e(key)}" rows="3" {"required" if required else ""}>{e(value)}</textarea></label>'

def select(key,label,options,current='',required=True):
    items=''.join(f'<option value="{e(v)}" {"selected" if str(v)==str(current) else ""}>{e(text)}</option>' for v,text in options)
    return f'<label>{e(label)}<select name="{e(key)}" {"required" if required else ""}>{items}</select></label>'

def check(key,label,on=False):
    return f'<label class="check"><input type="checkbox" name="{e(key)}" {"checked" if on else ""}>{e(label)}</label>'

def grid(body):
    return '<div class="fields">'+body+'</div>'

def card(title,body,head=''):
    return f'<section class="card"><div class="card-head"><h2>{e(title)}</h2>{head}</div>{body}</section>'

def table(headers,lines,empty='No records yet.'):
    if not lines:
        return f'<div class="empty">{e(empty)}</div>'
    return '<div class="table-scroll"><table><thead><tr>'+''.join('<th>'+e(h)+'</th>' for h in headers)+'</tr></thead><tbody>'+''.join('<tr>'+''.join('<td>'+str(cell)+'</td>' for cell in line)+'</tr>' for line in lines)+'</tbody></table></div>'

def pill(label,tone='soft'):
    return f'<span class="pill {tone}">{e(label)}</span>'

def order_badge(state):
    tone={'Review':'amber','Confirmed':'blue','Packing':'violet','Dispatched':'blue','Delivered':'green','Rejected':'red','Cancelled':'red','Expired':'red'}.get(state,'soft')
    return pill(state,tone)

def auth(r,title,body):
    return page(r,title,f'<main class="auth"><section class="auth-card">{brand(r,True)}<h1>{e(title)}</h1>{notice(r)}{body}</section></main>','auth-body')

def render_setup(r):
    body=inp('setup_key','Installation key',kind='password',required=True)+inp('name','Owner name',required=True)+inp('username','Username',required=True)
    body+=inp('password','Password (at least 12 characters)',kind='password',required=True,extra='autocomplete="new-password" minlength="12"')
    body+=inp('registration','Pharmacist registration number, if applicable')+check('demo','Load fictional demo products and pilot stock')
    return auth(r,'Set up your pharmacy',form(r,'setup',body+button('Create workspace'),cls='stack'))

def render_login(r):
    body=inp('username','Username',required=True,extra='autocomplete="username"')+inp('password','Password',kind='password',required=True,extra='autocomplete="current-password"')
    return auth(r,'Sign in',form(r,'login',body+button('Sign in'),cls='stack')+link(url(r,'/'),'Back to storefront','text'))

def render_error(r,message):
    return page(r,'Message',f'<main class="auth"><section class="auth-card"><h1>{e(message)}</h1>{link(url(r,"/admin" if r.user else "/"),"Go back")}</section></main>')

def metric(title,value,foot,tone):
    return f'<article class="metric {tone}"><span>{e(title)}</span><strong>{e(value)}</strong><small>{e(foot)}</small></article>'

def dashboard(r):
    db=r.db
    date_now=today()
    horizon=(datetime.now(TZ).date()+timedelta(days=90)).isoformat()
    sales=one(db,"SELECT COALESCE(SUM(subtotal+delivery),0) v FROM orders WHERE status='Delivered' AND SUBSTR(updated,1,10)=?",(date_now,))['v']
    queue=one(db,"SELECT COUNT(*) n FROM orders WHERE status='Review'")['n']
    low=one(db,'''SELECT COUNT(*) n FROM products p WHERE p.verified=1 AND p.min_stock >= (SELECT COALESCE(SUM(b.qty-b.reserved),0)
      FROM batches b JOIN branches br ON br.id=b.branch_id WHERE b.product_id=p.id AND b.hold=0 AND b.expiry>? AND br.active=1)''',(date_now,))['n']
    expiry=one(db,'SELECT COUNT(*) n FROM batches WHERE qty>0 AND expiry>? AND expiry<=?',(date_now,horizon))['n']
    ops=rows(db,"SELECT code,id,channel,created,status,subtotal+delivery total FROM orders ORDER BY id DESC LIMIT 7")
    exp=rows(db,'''SELECT p.brand,b.lot,b.expiry,b.qty FROM batches b JOIN products p ON p.id=b.product_id
                   WHERE qty>0 AND b.expiry<=? ORDER BY b.expiry LIMIT 7''',(horizon,))
    controls=(link(url(r,'/admin',page='pos'),'Open POS','bright') if r.allow('pos') else '')+link(url(r,'/'),'View storefront','glass')
    hero=f'<section class="admin-hero"><div class="hero-decor"></div><div><span class="kicker">PHARMACY WORKSPACE</span><h2>Welcome, {e(r.user["name"])}.</h2><p>Track counter sales, online orders and medicine stock in one place.</p><div class="actions">{controls}</div></div><span class="big-cross" aria-hidden="true">✚</span></section>'
    stats=metric("Today's sales",money(sales),'Delivered and counter sales','mint')+metric('Prescription queue',queue,'Waiting for a pharmacist','lavender')+metric('Low-stock products',low,'At or below reorder level','peach')+metric('Expiring batches',expiry,'Within the next 90 days','sky')
    order_link=link(url(r,'/admin',page='orders'),'View online orders','text') if r.allow('orders') else ''
    inv_link=link(url(r,'/admin',page='inventory'),'Batch inventory','text') if r.allow('inventory') else ''
    return hero+'<div class="metrics">'+stats+'</div><div class="board">'+card('Recent sales & orders',
        table(('Order','Channel','Status','Total'),[(e(o['code']),e(o['channel']),order_badge(o['status']),money(o['total'])) for o in ops],'Your first sale will appear here.'),order_link)+card('Expiry watch',
        table(('Product / lot','Expiry','Qty'),[(e(b['brand'])+'<small>'+e(b['lot'])+'</small>',e(b['expiry']),e(b['qty'])) for b in exp],'No batches are due within 90 days.'),inv_link)+'</div>'

def search_form(r,route,query='',admin=None,category=''):
    return f'<form class="search" method="get" action="{url(r,route)}">{hidden("page",admin) if admin else ""}{hidden("category",category) if category else ""}<input name="q" value="{e(query)}" placeholder="Search brand, generic, company or barcode" aria-label="Search products">{button("Search")}</form>'

def pager(r,route,current,count,page_id=None,**params):
    total=math.ceil(count/30)
    if total<=1:
        return ''
    if page_id:
        params['page']=page_id
    prev=link(url(r,route,p=current-1,**params),'Previous') if current>1 else ''
    nxt=link(url(r,route,p=current+1,**params),'Next') if current<total else ''
    return f'<div class="pager">{prev}<span>Page {current:,} of {total:,}</span>{nxt}</div>'

def pages(r):
    try:
        return max(1,min(10000,int(r.query.get('p','1'))))
    except ValueError:
        return 1

def product_label(p):
    return ' '.join(str(p[k]) for k in ('brand','strength','form') if p[k])

def product_form(r,p):
    get=p.get
    identifiers=grid(''.join(inp(k,label,get(k,''),required=k in ('sku','brand')) for k,label in (
        ('sku','SKU'),('barcode','Barcode'),('brand','Brand name'),('brand_bn','Brand name in Bangla'),('generic','Generic name'),
        ('generic_bn','Generic name in Bangla'),('maker','Manufacturer'),('dar','DAR / MA number'),('strength','Strength'),('form','Dosage form'),('release','Release type'))))
    variants=grid(select('category','Category',[(s,s) for s in CATEGORIES],get('category','Medicine'))+
        select('classification','Sale class',list(CLASSES.items()),get('classification','pending'))+
        inp('pack','Pack label',get('pack',''))+inp('pack_units','Base units per pack',get('pack_units',1),'number',True,extra='min="1"')+
        inp('sale_unit','Base sale unit (e.g. tablet)',get('sale_unit','unit'),required=True)+
        inp('mrp','MRP per base unit (BDT)',f'{get("mrp",0)/100:.2f}','number',True,extra='min="0" step="0.01"')+
        inp('price','Sale price per base unit (BDT)',f'{get("price",0)/100:.2f}','number',True,extra='min="0" step="0.01"')+
        inp('min_stock','Reorder level',get('min_stock',5),'number',True,extra='min="0"'))
    source=grid(inp('source','Data source',get('source',''))+inp('source_url','Source URL',get('source_url',''),'url')+inp('image_url','Licensed pack image URL',get('image_url',''),'url'))
    clinical=json.loads(get('clinical','{}'))
    details='<details class="subpanel"><summary>Clinical reference & leaflet</summary>'+grid(''.join(
        textarea(k,k.replace('_',' ').capitalize(),clinical.get(k,'')) if k!='leaflet_url' else inp(k,'Approved leaflet URL',clinical.get(k,''),'url') for k in CLINICAL))+'</details>'
    flags='<div class="actions">'+check('verified','Verified by registered pharmacist',get('verified'))+check('online','List online',get('online'))+check('cold','Temperature-sensitive',get('cold'))+'</div>'
    return form(r,'product',hidden('id',get('id',''))+identifiers+variants+source+details+flags+button('Save medicine'),cls='stack')

def catalog(r):
    q=r.query.get('q','')[:160]
    matches,count=search(r.db,q,page=pages(r))
    editing=r.query.get('edit')
    choice=one(r.db,'SELECT * FROM products WHERE id=?',(integer(editing),)) if editing and editing!='new' else None
    if editing and editing!='new' and not choice:
        raise Invalid('Medicine not found.')
    editor=card('Edit medicine' if choice else 'Add a medicine',product_form(r,dict(choice) if choice else {}),link(url(r,'/admin',page='catalog'),'Close','text')) if editing else ''
    importing='<details class="subpanel"><summary>Import MedEx or supplier catalog</summary><p>Upload your authorised CSV or Excel catalog mapped to the template. Imported rows stay hidden until verified.</p><p><a href="https://medex.com.bd/generics?page=84">MedEx generics ↗</a> · <a href="https://medex.com.bd/brands">MedEx brands ↗</a></p>'
    importing+=form(r,'import_preview',inp('csv','Catalog CSV or XLSX (up to 25 MB)',kind='file',required=True,extra='accept=".csv,.xlsx,text/csv"')+button('Preview import'),files=True,cls='inline')
    pending=r.session.get('import')
    if pending:
        importing+=f'<p><b>{pending["count"]:,} validated rows</b></p><ul>'+''.join('<li>'+e(s)+'</li>' for s in pending['example'])+'</ul>'
        importing+=form(r,'import_apply',button('Apply import'))
    importing+='</details>'
    listing=table(('Medicine / SKU','Generic / manufacturer','Sale class','Price','Available',''),[
      (f'<b>{e(product_label(p))}</b><small>{e(p["sku"])}</small>',f'{e(p["generic"])}<small>{e(p["maker"])}</small>',
       pill(CLASSES[p['classification']],'green' if p['verified'] else 'amber'),money(p['price']),e(p['available']),
       link(url(r,'/admin',page='catalog',edit=p['id']),'Edit','text')) for p in matches],'No matching catalog entries.')
    actions=link(url(r,'/admin/template'),'CSV template')+link(url(r,'/admin',page='catalog',edit='new'),'+ Add medicine','primary')
    return editor+card('Medicine directory',search_form(r,'/admin',q,'catalog')+f'<p class="muted">{count:,} variants</p>'+listing+
        pager(r,'/admin',pages(r),count,'catalog',q=q)+importing,actions)

def generics(r):
    q=r.query.get('q','').strip()[:160]
    pattern='%'+q+'%'
    count=one(r.db,'SELECT COUNT(*) n FROM generics WHERE name LIKE ? OR bangla LIKE ?',(pattern,pattern))['n']
    records=rows(r.db,'''SELECT g.*, (SELECT COUNT(*) FROM product_generics pg WHERE pg.generic_id=g.id) variants
      FROM generics g WHERE name LIKE ? OR bangla LIKE ? ORDER BY name COLLATE NOCASE LIMIT 30 OFFSET ?''',(pattern,pattern,(pages(r)-1)*30))
    selected=r.query.get('id')
    details=''
    if selected:
        g=one(r.db,'SELECT * FROM generics WHERE id=?',(integer(selected),))
        if not g:
            raise Invalid('Generic not found.')
        products=rows(r.db,'SELECT p.* FROM products p JOIN product_generics pg ON pg.product_id=p.id WHERE pg.generic_id=? ORDER BY p.brand LIMIT 100',(g['id'],))
        variants=table(('Brand variant','Company','SKU'),[(link(url(r,'/admin',page='catalog',edit=p['id']),product_label(p),'text'),e(p['maker']),e(p['sku'])) for p in products])
        structural=grid(inp('bangla','Name in Bangla',g['bangla'])+inp('drug_class','Drug class',g['drug_class'])+
          inp('source_url','Licensed source URL',g['source_url'],'url')+textarea('ingredients','Active ingredients and combination',g['ingredients']))
        observed=json.loads(g['clinical'])
        labels=grid(''.join(inp(k,k.replace('_',' ').title(),observed.get(k,''),'url') if k=='leaflet_url' else textarea(k,k.replace('_',' ').title(),observed.get(k,'')) for k in CLINICAL))
        editor=''
        if r.user['role'] in ('owner','pharmacist') and r.user['registration']:
            editor='<details class="subpanel"><summary>Verify generic reference</summary>'+form(r,'generic',hidden('id',g['id'])+structural+labels+button('Save generic reference'),cls='stack')+'</details>'
        details=card(g['name'],f'<p>{e(g["bangla"])} · {e(g["drug_class"] or "Class pending")}</p>'+variants+editor)
    lines=[(e(g['name']),e(g['bangla']),e(g['variants']),e(g['verified_on'] or 'Pending'),
            link(url(r,'/admin',page='generics',id=g['id']),'View variants','text')) for g in records]
    return details+card('Browse generics',search_form(r,'/admin',q,'generics')+table(('Generic','বাংলা','Brand variants','Verified',''),lines)+
        pager(r,'/admin',pages(r),count,'generics',q=q),
        link('https://medex.com.bd/generics?page=84','MedEx source ↗','secondary'))

def branches(r):
    return [(x['id'],x['name']) for x in rows(r.db,'SELECT id,name FROM branches WHERE active=1 ORDER BY id')]

def inventory(r):
    day=today()
    q=r.query.get('q','').strip()[:120]
    bids=r.query.get('branch','')
    choices=branches(r)
    filters=[]
    params=[]
    if q:
        filters.append('(p.brand LIKE ? OR p.sku LIKE ? OR b.lot LIKE ? OR p.generic LIKE ?)')
        params.extend(['%'+q+'%']*4)
    if bids:
        filters.append('b.branch_id=?')
        params.append(integer(bids))
    where=' WHERE '+' AND '.join(filters) if filters else ''
    batches=rows(r.db,'''SELECT b.*,p.brand,p.sku,br.name branch_name FROM batches b JOIN products p ON p.id=b.product_id
        JOIN branches br ON br.id=b.branch_id'''+where+' ORDER BY b.expiry,b.id LIMIT 300',params)
    searcher=f'<form class="inline" action="{url(r,"/admin")}">{hidden("page","inventory")}'+inp('q','Product, SKU or lot',q)+select('branch','Branch',[('','All branches'),*choices],bids,False)+button('Filter')+'</form>'
    data=[]
    for b in batches:
        expired=b['expiry']<=day
        state='Expired' if expired else 'On hold' if b['hold'] else 'Sellable'
        actions='<details><summary>Manage batch</summary>'
        if not expired:
            actions+=form(r,'batch_hold',hidden('id',b['id'])+hidden('hold',0 if b['hold'] else 1)+inp('reason','Reason',required=True)+button('Release' if b['hold'] else 'Hold','secondary'),cls='stack')
        if not expired and not b['hold'] and len(choices)>1:
            actions+=form(r,'transfer',hidden('id',b['id'])+select('branch','To branch',[(k,v) for k,v in choices if k!=b['branch_id']])+inp('quantity','Base units',kind='number',required=True,extra='min="1"')+button('Transfer','secondary'),cls='stack')
        actions+=form(r,'stock_count',hidden('id',b['id'])+inp('quantity','Physical units counted',b['qty'],'number',True,extra='min="0"')+
             inp('reason','Count reference',required=True)+button('Record count','secondary'),cls='stack')
        actions+=link(url(r,'/admin',page='inventory',trace=b['id']),'Trace issued orders','text')
        if b['purchase_id'] and b['qty']>b['reserved']:
            actions+=form(r,'supplier_return',hidden('id',b['id'])+inp('quantity','Supplier return units',kind='number',required=True,extra='min="1"')+
                 inp('credit','Supplier credit (BDT)',0,'number',True,extra='min="0" step=".01"')+inp('reason','Return reference',required=True)+button('Return to supplier','secondary'),cls='stack')
        actions+='</details>'
        data.append((f'<b>{e(b["brand"])}</b><small>{e(b["sku"])}</small>',e(b['branch_name']),e(b['lot']),e(b['expiry']),e(b['shelf']),e(b['qty']),e(b['reserved']),pill(state,'red' if expired or b['hold'] else 'green'),actions))
    activity=rows(r.db,'''SELECT p.brand,b.lot,m.delta,m.reason,m.ref,m.created FROM movements m
        JOIN batches b ON b.id=m.batch_id JOIN products p ON p.id=b.product_id ORDER BY m.id DESC LIMIT 25''')
    movements=table(('Product','Lot','Change','Reason','Reference','Date'),[(e(m['brand']),e(m['lot']),e(m['delta']),e(m['reason']),e(m['ref']),e(m['created'][:16].replace('T',' '))) for m in activity])
    trace=''
    if r.query.get('trace'):
        trace_id=integer(r.query['trace'])
        history=rows(r.db,'''SELECT o.code,o.channel,o.status,o.created,l.qty,l.returned FROM orders o JOIN lines l ON l.order_id=o.id
           WHERE l.batch_id=? ORDER BY o.created DESC''',(trace_id,))
        trace=card(f'Batch #{trace_id} order trace',table(('Order','Channel','Status','Date','Units','Returned'),
             [(e(h['code']),e(h['channel']),order_badge(h['status']),e(h['created'][:10]),e(h['qty']),e(h['returned'])) for h in history]))
    return trace+card('Stock by batch',searcher+table(('Product','Branch','Batch','Expires','Shelf','On hand','Reserved','Status','Actions'),data))+card('Stock movement history',movements)

def supplier_screen(r):
    data=rows(r.db,'SELECT * FROM suppliers ORDER BY name')
    entry=grid(inp('name','Supplier name',required=True)+inp('phone','Phone',kind='tel')+inp('address','Address'))+button('Add supplier')
    return card('Suppliers',form(r,'supplier',entry,cls='stack')+table(('Supplier','Phone','Address'),[(e(x['name']),e(x['phone']),e(x['address'])) for x in data]))

def purchase_metrics(r):
    return rows(r.db,'''SELECT p.id,p.reference,p.created,s.name supplier,b.name branch,
         COALESCE((SELECT SUM(received_qty*cost) FROM batches WHERE purchase_id=p.id),0) total,
         COALESCE((SELECT SUM(amount) FROM payments WHERE purchase_id=p.id),0) paid,
         COALESCE((SELECT SUM(sr.credit) FROM supplier_returns sr JOIN batches sb ON sb.id=sr.batch_id WHERE sb.purchase_id=p.id),0) credit
         FROM purchases p LEFT JOIN suppliers s ON s.id=p.supplier_id JOIN branches b ON b.id=p.branch_id ORDER BY p.id DESC LIMIT 200''')

def purchases(r):
    suppliers=[(x['id'],x['name']) for x in rows(r.db,'SELECT * FROM suppliers ORDER BY name')]
    q=r.query.get('q','')[:120]
    products,_=search(r.db,q,size=30)
    opts=[(p['id'],product_label(p)+' · '+p['sku']) for p in products]
    body=search_form(r,'/admin',q,'purchases')
    if suppliers and opts:
        entry=grid(select('supplier','Supplier',suppliers)+select('branch','Branch',branches(r))+inp('reference','Supplier invoice number',required=True)+
            select('product','Product (use search above)',opts)+inp('lot','Batch / lot',required=True)+inp('expiry','Expiry date',kind='date',required=True)+
            inp('manufactured','Manufacturing date',kind='date')+inp('shelf','Shelf location')+inp('quantity','Base units received',kind='number',required=True,extra='min="1"')+
            inp('cost','Purchase cost per base unit',kind='number',required=True,extra='min="0" step=".01"'))+button('Receive batch')
        body+=form(r,'receive',entry,cls='stack')
    else:
        body+='<p class="empty">Add a supplier and select a catalog product to receive stock.</p>'
    return card('Receive a purchase batch',body)+card('Supplier invoices',table(('Invoice','Supplier','Branch','Received','Total','Outstanding'),[
      (e(x['reference']),e(x['supplier']),e(x['branch']),e(x['created'][:10]),money(x['total']),money(x['total']-x['paid']-x['credit'])) for x in purchase_metrics(r)]))

def pos(r):
    q=r.query.get('q','')[:120]
    items,_=search(r.db,q,size=30)
    products=[p for p in items if p['verified'] and p['classification'] not in ('blocked','pending')]
    names=branches(r)
    body=search_form(r,'/admin',q,'pos')
    lookup=f'<div class="live-pos" hidden data-lookup="{url(r,"/admin/lookup")}"><label>Find or scan a product<input data-pos-search type="search" placeholder="Brand, generic, SKU or barcode" autocomplete="off"></label><div data-pos-results role="status"></div><p class="muted">Selected items stay in this sale while you search.</p></div>'
    lines=[]
    for p in products:
        lines.append((f'<b>{e(product_label(p))}</b><small>{e(p["sku"])} · {e(p["sale_unit"])}</small>',pill(CLASSES[p['classification']]),money(p['price']),e(p['available']),
           f'<input class="quantity" type="number" name="qty_{p["id"]}" min="0" max="10000" inputmode="numeric" data-price="{p["price"]}" aria-label="Quantity for {e(product_label(p))}">'+
           (f'<button class="chip qty-pack" type="button" data-pack="{p["pack_units"]}">+ pack</button>' if p['pack_units']>1 else '')))
    inputs=grid(select('branch','Branch',names)+inp('customer','Customer name (optional)')+select('payment','Payment',[(x,x) for x in ('Cash','bKash','Nagad','Card')]))
    listing=table(('Product','Sale class','Unit price','Available across branches','Quantity'),lines)
    rx='<details class="subpanel"><summary>Prescription verification for Rx items</summary>'+inp('rx','Prescription JPG, PNG or PDF',kind='file',extra='accept="image/jpeg,image/png,application/pdf"')+check('rx_checked','I verified the original prescription and ordered items')+'</details>'
    pay='<div class="payline"><span>Sale total <b id="pos-total">৳0.00</b></span>'+button('Complete sale & print')+'</div>'
    fallback=f'<div data-pos-fallback>{listing}</div>'
    cart='<div data-pos-cart hidden class="table-scroll"><table><thead><tr><th>Item</th><th>Price</th><th>Base units</th><th></th></tr></thead><tbody></tbody></table></div>'
    return card('Counter sale',f'<div data-pos-legacy>{body}</div>'+form(r,'pos',hidden('submission',secrets.token_hex(16))+inputs+lookup+fallback+cart+rx+pay,files=True,cls='stack pos-form'))

def orders(r):
    selected=r.query.get('order')
    if selected:
        o=one(r.db,"SELECT * FROM orders WHERE id=? AND channel='Online'",(integer(selected),))
        if not o:
            raise Invalid('Order not found.')
        lines=rows(r.db,'SELECT * FROM lines WHERE order_id=?',(o['id'],))
        details=f'<div class="order-meta">{order_badge(o["status"])}<b>{e(o["customer"])}</b><span>{e(o["phone"])}</span><span>{e(o["address"])}</span><span>{money(o["subtotal"]+o["delivery"])} · {e(o["payment"])}</span></div>'
        if o['review_note']:
            details+='<p>'+e(o['review_note'])+'</p>'
        if o['rx_file'] and r.allow('rx'):
            details+=link(url(r,'/admin/rx',order=o['id']),'Download private prescription')
        status=o['status']
        targets={'Review':('Confirmed','Rejected','Cancelled'),'Confirmed':('Packing','Cancelled'),'Packing':('Dispatched','Cancelled'),'Dispatched':('Delivered',)}.get(status,())
        actions=[]
        for target in targets:
            if ((status=='Review' and target in ('Confirmed','Rejected')) or target=='Dispatched') and not (r.allow('rx') and r.user['registration']):
                continue
            inputs=hidden('id',o['id'])+hidden('target',target)
            if status=='Review' and target=='Confirmed':
                inputs+=check('checked','Prescription, quantity and exact products verified')
            if target in ('Rejected','Cancelled'):
                inputs+=inp('note','Reason or gateway refund/void reference',required=target=='Rejected')
                if o['payment']=='SSLCommerz':
                    inputs+=check('checked_refund','Gateway transaction reconciled and any payment refunded')
            if target=='Dispatched':
                inputs+=inp('tracking','Courier tracking number')
            actions.append(form(r,'order_status',inputs+button(target,'secondary' if target in ('Cancelled','Rejected') else 'primary'),cls='stack action-panel'))
        if r.allow('invoice') and status in ('Delivered','Dispatched'):
            actions.append(link(url(r,'/admin/invoice',order=o['id']),'Print invoice'))
        items=[]
        for l in lines:
            refund=''
            if status=='Delivered' and l['qty']>l['returned'] and r.user['role'] in ('owner','manager','pharmacist'):
                refund='<details><summary>Return item</summary>'+form(r,'return',hidden('line',l['id'])+inp('quantity','Qty',kind='number',required=True,extra=f'min="1" max="{l["qty"]-l["returned"]}"')+inp('note','Reason',required=True)+button('Record return','secondary'),cls='stack')+'</details>'
            items.append((e(l['name']),e(l['lot']),e(l['expiry']),e(l['qty']),e(l['returned']),money(l['price']),refund))
        return card(o['code'],details+table(('Product','Batch','Expiry','Qty','Returned','Unit price','Return'),items)+'<div class="actions wrap">'+''.join(actions)+'</div>',link(url(r,'/admin',page='orders'),'Back to orders','text'))
    state=r.query.get('state','')
    valid=('Review','Confirmed','Packing','Dispatched','Delivered','Rejected','Cancelled','Expired')
    if state and state not in valid:
        raise Invalid('Invalid order filter.')
    data=rows(r.db,"SELECT * FROM orders WHERE channel='Online' AND (?='' OR status=?) ORDER BY id DESC LIMIT 200",(state,state))
    tabs='<div class="chips">'+''.join(link(url(r,'/admin',page='orders',state=x),x or 'All','selected' if x==state else 'secondary') for x in ('',*valid))+'</div>'
    return card('Online order queue',tabs+table(('Order / date','Customer','Delivery area','Total','Status',''),[
      (f'<b>{e(o["code"])}</b><small>{e(o["created"][:16].replace("T"," "))}</small>',e(o['customer']),e(o['zone']),money(o['subtotal']+o['delivery']),
       order_badge(o['status']),link(url(r,'/admin',page='orders',order=o['id']),'Open','text')) for o in data]))

def report(r):
    db=r.db
    sales=rows(db,'''SELECT channel,payment,COUNT(*) n, SUM(subtotal) gross,SUM(delivery) delivery FROM orders
        WHERE status='Delivered' GROUP BY channel,payment ORDER BY channel,payment''')
    ledger=one(db,'''SELECT COALESCE(SUM((l.qty-l.returned)*(l.price-l.cost)),0) margin,COALESCE(SUM(l.returned*l.price),0) refunds
         FROM lines l JOIN orders o ON o.id=l.order_id WHERE o.status='Delivered' ''')
    inventory_value=one(db,'SELECT COALESCE(SUM(qty*cost),0) n FROM batches WHERE qty>0 AND expiry>? AND hold=0',(today(),))['n']
    panels=metric('Gross product margin',money(ledger['margin']),'After recorded returns, before expenses','mint')+metric('Returned sales value',money(ledger['refunds']),'Recorded customer returns','peach')+metric('Sellable stock cost',money(inventory_value),'Unexpired batches across branches','sky')
    rendered=card('Sales and collections',table(('Channel','Payment','Sales','Products (gross)','Delivery'),[(e(s['channel']),e(s['payment']),e(s['n']),money(s['gross']),money(s['delivery'])) for s in sales]))
    invoices=[]
    for x in purchase_metrics(r):
        due=x['total']-x['paid']-x['credit']
        entry=''
        if due:
            entry='<details><summary>Record payment</summary>'+form(r,'supplier_payment',hidden('purchase',x['id'])+inp('amount','Amount (BDT)',kind='number',required=True,extra='min=".01" step=".01"')+inp('reference','Payment reference',required=True)+button('Save payment','secondary'),cls='stack')+'</details>'
        invoices.append((e(x['reference']),e(x['supplier']),money(x['total']),money(x['paid']),money(x['credit']),money(due),entry))
    closes=rows(db,'SELECT c.*,b.name branch FROM closings c JOIN branches b ON b.id=c.branch_id ORDER BY c.sale_date DESC LIMIT 100')
    close_form=form(r,'cash_close',grid(select('branch','Branch',branches(r))+inp('date','Business date',today(),'date',True)+
       inp('counted','Counted sales cash (BDT)',kind='number',required=True,extra='min="0" step=".01"')+inp('note','Note'))+button('Record cash closing'),cls='stack')
    close_table=table(('Date','Branch','Expected','Counted','Difference','Note'),[(e(c['sale_date']),e(c['branch']),money(c['expected']),money(c['counted']),money(c['counted']-c['expected']),e(c['note'])) for c in closes])
    return '<div class="metrics three">'+panels+'</div>'+rendered+card('Cash closing',close_form+close_table)+card('Supplier balance',table(('Invoice','Supplier','Purchase cost','Paid','Credits','Due','Payment'),invoices))

def settings(r):
    keys={'store':'Store name','license':'Online pharmacy licence','retail_license':'Retail / model pharmacy licence','address':'Pharmacy address','phone':'Contact phone','owner':'Owner / company','pharmacist':'Responsible pharmacist','registration':'Pharmacist registration','pharmacist_photo':'Pharmacist photo (HTTPS URL)','hours':'Service hours','logistics':'Logistics provider'}
    body=grid(''.join(inp(k,label,r.setting.get(k,''),'url' if k=='pharmacist_photo' else 'text') for k,label in keys.items())+
         inp('license_expiry','Online licence expiry',r.setting.get('license_expiry',''),'date')+
         select('mode','Store mode',[('draft','Draft'),('demo','Pilot demo'),('live','Live storefront')],r.setting.get('mode','draft'))+
         select('accent','Workspace theme',[('forest','Forest'),('ocean','Ocean'),('violet','Violet')],r.setting.get('accent','forest')))
    body+=textarea('return_policy','Return policy',r.setting.get('return_policy',''))+button('Save settings')
    zones=rows(r.db,'SELECT z.*, b.name branch FROM zones z JOIN branches b ON b.id=z.branch_id ORDER BY z.id')
    zone_entry=form(r,'zone',grid(inp('name','Zone name',required=True)+inp('fee','Delivery fee (BDT)',kind='number',required=True,extra='min="0" step=".01"')+
       inp('eta','Delivery estimate',required=True)+select('branch','Fulfilment branch',branches(r)))+button('Add zone'),cls='stack')
    branch_entry=form(r,'branch',grid(inp('name','Branch name',required=True)+inp('address','Address',required=True))+button('Add branch'),cls='stack')
    return card('Store identity & licensing',form(r,'settings',body,cls='stack'))+card('Branches',branch_entry+table(('Branch','Address'),[(e(b['name']),e(b['address'])) for b in rows(r.db,'SELECT * FROM branches')]))+card('Delivery zones',zone_entry+table(('Zone','Branch','Fee','ETA',''),[
       (e(z['name']),e(z['branch']),money(z['fee']),e(z['eta']),form(r,'zone_toggle',hidden('id',z['id'])+button('Disable' if z['active'] else 'Enable','secondary'))) for z in zones]))

def staff(r,permissions):
    roles=[(k,k.replace('_',' ').title()) for k in permissions if k!='owner']
    fields=grid(inp('name','Full name',required=True)+inp('username','Username',required=True)+inp('password','Password',kind='password',required=True,extra='minlength="12" autocomplete="new-password"')+
        select('role','Role',roles)+inp('registration','Pharmacist registration (for pharmacist accounts)'))
    team=rows(r.db,'SELECT id,name,username,role,registration,active FROM users ORDER BY id')
    return card('Manage staff',form(r,'staff',fields+button('Create staff account'),cls='stack')+table(('Name','Username','Role','Registration','Status',''),[
        (e(u['name']),e(u['username']),e(u['role'].replace('_',' ').title()),e(u['registration']),pill('Active' if u['active'] else 'Disabled','green' if u['active'] else 'red'),
         form(r,'staff_toggle',hidden('id',u['id'])+button('Disable' if u['active'] else 'Enable','secondary')) if u['role']!='owner' else '—') for u in team]))

def tickets(r):
    data=rows(r.db,'SELECT * FROM tickets ORDER BY id DESC LIMIT 200')
    return card('Support & complaints',table(('Order','Customer phone','Message','Status','Resolution'),[
      (e(t['code']),e(t['phone']),e(t['body']),pill(t['status'],'amber' if t['status']=='Open' else 'green'),
       form(r,'ticket_close',hidden('id',t['id'])+textarea('resolution','Resolution',required=True)+button('Resolve','secondary'),cls='stack') if t['status']=='Open' else e(t['resolution']))
      for t in data]))

def activity(r):
    data=rows(r.db,'SELECT a.*,u.name FROM audit a LEFT JOIN users u ON u.id=a.user_id ORDER BY a.id DESC LIMIT 250')
    return card('Audit trail',table(('Date','User','Action','Detail'),[(e(x['created'][:19].replace('T',' ')),e(x['name'] or 'System'),e(x['action']),e(x['detail'])) for x in data]))

ICONS={'dashboard':'◫','pos':'▤','orders':'▱','catalog':'✚','generics':'⌘','inventory':'▦','purchases':'↓','suppliers':'◇','reports':'◈','tickets':'▧','settings':'⚙','staff':'♙','audit':'≡'}

def render_admin(r,key,nav,roles):
    title=next(group[key] for group in nav.values() if key in group)
    routes={'dashboard':dashboard,'pos':pos,'orders':orders,'catalog':catalog,'generics':generics,'inventory':inventory,'purchases':purchases,
            'suppliers':supplier_screen,'reports':report,'settings':settings,'staff':lambda req:staff(req,roles),'tickets':tickets,'audit':activity}
    sidebar=brand(r,True)
    for group,links in nav.items():
        sidebar+=f'<div class="nav-label">{e(group)}</div><nav aria-label="{e(group)}">'
        for ident,label in links.items():
            if r.allow(ident):
                sidebar+=f'<a href="{url(r,"/admin",page=ident)}" class="{"active" if ident==key else ""}" {"aria-current=page" if ident==key else ""}><span aria-hidden="true">{ICONS[ident]}</span>{e(label)}</a>'
        sidebar+='</nav>'
    sidebar+='<div class="side-bottom">'+link(url(r,'/'),'↗ View storefront','side-link')+form(r,'logout',button('Sign out','side-link'))+'</div>'
    user=e(r.user['name'])
    role=e(r.user['role'].replace('_',' ').title())
    initials=e(''.join(p[0].upper() for p in r.user['name'].split()[:2]))
    theme=r.setting.get('accent') or 'forest'
    running=mode(r.setting)
    flag=pill('Live storefront','green') if running=='live' else pill('Pilot demo' if running=='demo' else 'Draft store','amber')
    header=f'<header class="admin-header"><button type="button" class="hamburger" data-menu aria-expanded="false" aria-controls="sidebar" aria-label="Menu">☰</button><div class="heading"><span class="kicker">ASTHA PHARMACY SOFT</span><h1>{e(title)}</h1></div>{flag}<div class="user"><b class="avatar">{initials}</b><div><strong>{user}</strong><small>{role}</small></div></div></header>'
    main=routes[key](r)
    return page(r,title,f'<button class="scrim" type="button" data-close aria-label="Close menu"></button><aside class="sidebar" id="sidebar">{sidebar}</aside><div class="workspace">{header}<main class="admin-main">{notice(r)}{main}<footer>Astha Pharmacy Soft by Zeekodes</footer></main></div>','admin theme-'+theme)

def render_invoice(r,o):
    lines=rows(r.db,'SELECT * FROM lines WHERE order_id=? ORDER BY id',(o['id'],))
    records=[(e(l['name']),e(l['maker']),e(l['dar']),e(l['lot']),e(l['manufactured']),e(l['expiry']),f'{l["qty"]} {e(l["sale_unit"])}',money(l['price']),money(l['qty']*l['price'])) for l in lines]
    rows_html=table(('Product','Manufacturer','DAR / MA','Batch','Mfg.','Expiry','Qty','Unit price','Amount'),records)
    title='Sales invoice' if o['status']=='Delivered' else 'Dispatch invoice'
    pharmacy=e(r.setting.get('store','Astha Pharmacy'))
    identity=f'<p>{e(o["branch"])} · {e(o["branch_address"])} <br>Phone {e(r.setting.get("phone","—"))} · Licence {e(r.setting.get("license") or r.setting.get("retail_license") or "—")}<br>Owner {e(r.setting.get("owner","—"))}</p>'
    pharmacist=f'<p>Dispensed by {e(o["pharmacist_name"] or "—")} · Registration {e(o["pharmacist_reg"] or "—")}</p><p>Pharmacist signature ___________________</p>'
    return_entry=''
    if o['channel']=='POS' and o['status']=='Delivered' and r.user['role'] in ('owner','manager','pharmacist'):
        return_list=[]
        for l in lines:
            if l['qty']>l['returned']:
                return_list.append(form(r,'return',hidden('invoice',o['id'])+hidden('line',l['id'])+
                    inp('quantity','Return '+l['name'],kind='number',required=True,extra=f'min="1" max="{l["qty"]-l["returned"]}"')+
                    inp('note','Reason',required=True)+button('Record return','secondary'),path='/admin',cls='inline'))
        if return_list:
            return_entry='<div class="no-print">'+card('Counter sale returns',''.join(return_list))+'</div>'
    return page(r,title,f'<main class="invoice"><div class="actions no-print">{link(url(r,"/admin"),"Back to workspace")}<button type="button" class="btn primary" data-print>Print / Save PDF</button></div><section class="card"><h1>{pharmacy}</h1>{identity}<h2>{title}</h2><p>{e(o["code"])} · {e(o["created"][:19].replace("T"," "))} · {e(o["payment"])}<br>Customer {e(o["customer"])}</p>{rows_html}<div class="invoice-total"><div>Subtotal <b>{money(o["subtotal"])}</b></div><div>Delivery <b>{money(o["delivery"])}</b></div><div>Total <b>{money(o["subtotal"]+o["delivery"])}</b></div></div>{pharmacist}</section>{return_entry}</main>')

CATEGORY_ICONS={'Medicine':'✚','Medical Devices':'◇','Baby Care':'♡','Personal Care':'✧','Health Essentials':'▧'}

def public_info(r):
    if mode(r.setting)!='live':
        return ''
    labels={'license':'Online licence','retail_license':'Retail licence','address':'Address','phone':'Phone','hours':'Hours','owner':'Owner',
            'pharmacist':'Responsible pharmacist','registration':'Pharmacist registration','logistics':'Logistics provider'}
    content=''.join(f'<div><small>{e(label)}</small><b>{e(r.setting.get(k,""))}</b></div>' for k,label in labels.items())
    photo=f'<img src="{e(r.setting.get("pharmacist_photo"))}" alt="Responsible pharmacist" class="pharmacist-photo" loading="lazy">'
    return f'<section class="public-details">{photo}<div>{content}{link(url(r,"/policy"),"Return policy","text")}</div></section>'

def storefront(r):
    current=mode(r.setting)
    q=r.query.get('q','').strip()[:160]
    category=r.query.get('category','')
    if category and category not in CATEGORIES:
        raise Invalid('Category unavailable.')
    hero=''
    if not q and not category:
        hero='<section class="store-hero"><div class="store-hero-copy"><span class="kicker">ASTHA PHARMACY</span><h1>Everyday care, closer to home.</h1><p>Search for medicines by brand or generic name and shop healthcare essentials.</p><div class="actions">'+link(url(r,'/',category='Medicine'),'Browse medicines','primary')+link(url(r,'/cart')+'#prescription','Upload prescription','secondary')+'</div></div><div class="store-art" aria-hidden="true"><span class="art-dot one"></span><span class="art-dot two"></span><span class="art-tile"><span>✚</span></span><span class="art-capsule"></span></div></section>'
    if current=='draft':
        return hero+card('Online orders are paused','<p>Contact the pharmacy for availability and service information.</p>')
    goods,count=search(r.db,q,public=True,category=category,page=pages(r))
    if current=='live':
        public='Live'
        clause,args=search_sql(q)
        params=list(args)
        category_filter=''
        if category:
            category_filter=' AND p.category=?'
            params.append(category)
        visible="p.source<>'Demo' AND p.online=1 AND p.verified=1 AND p.cold=0 AND p.classification IN ('otc','rx','general')"
        count=one(r.db,f'SELECT COUNT(*) n FROM products p WHERE {visible} AND ({clause})'+category_filter,params)['n']
        goods=rows(r.db,f'''SELECT p.*,COALESCE(SUM(CASE WHEN b.expiry>? AND b.hold=0 AND br.active=1 THEN b.qty-b.reserved ELSE 0 END),0) available
                FROM products p LEFT JOIN batches b ON b.product_id=p.id LEFT JOIN branches br ON br.id=b.branch_id
                WHERE {visible} AND ({clause}){category_filter} GROUP BY p.id ORDER BY p.brand COLLATE NOCASE,p.id LIMIT 30 OFFSET ?''',
                [today(),*params,(pages(r)-1)*30])
    display=''.join(product_tile(r,p) for p in goods)
    nav='<div class="category-nav">'+link(url(r,'/'),'All products','selected' if not category else 'secondary')+''.join(
        link(url(r,'/',category=c,q=q),CATEGORY_ICONS[c]+' '+c,'selected' if c==category else 'secondary') for c in CATEGORIES)+'</div>'
    labels=category or ('Search results' if q else 'Shop healthcare')
    return hero+nav+f'<div class="section-title"><h2>{e(labels)}</h2><span>{count:,} products</span></div>'+(
        f'<div class="product-grid">{display}</div>' if display else '<div class="empty">No products found. Try a brand or generic name.</div>')+pager(r,'/',pages(r),count,q=q,category=category)

def product_tile(r,p):
    visual=f'<img src="{e(p["image_url"])}" alt="" loading="lazy">' if p['image_url'] else f'<span aria-hidden="true">{CATEGORY_ICONS.get(p["category"],"✚")}</span>'
    href=url(r,'/product',id=p['id'])
    cclass=['mint','sky','lavender','peach'][p['id']%4]
    badge=pill('Prescription required','violet') if p['classification']=='rx' else pill(p['category'])
    add=form(r,'cart_add',hidden('id',p['id'])+button('Add to cart','primary small'),path='/') if p['available'] else pill('Out of stock','amber')
    sale=f'<div class="tile-bottom"><strong>{money(p["price"])} <small>/{e(p["sale_unit"])}</small></strong>{add}</div>'
    return f'<article class="product"><a href="{href}" class="tile-image {cclass}" aria-label="{e(product_label(p))}">{visual}</a><div class="tile-copy">{badge}<h3><a href="{href}">{e(product_label(p))}</a></h3><p>{e(p["generic"] or p["maker"])} · {e(p["pack"] or p["sale_unit"])}</p>{sale}</div></article>'

def view_product(r):
    if mode(r.setting)=='draft':
        return card('Catalogue unavailable','<p>Online product listings are closed.</p>')
    p=one(r.db,"SELECT * FROM products WHERE id=? AND online=1 AND verified=1 AND cold=0 AND classification IN ('otc','rx','general')",
        (integer(r.query.get('id')),))
    if not p or (mode(r.setting)=='live' and p['source']=='Demo'):
        return card('Product unavailable',link(url(r,'/'),'Browse products'))
    variant=''.join(f'<div><dt>{e(label)}</dt><dd>{e(p[key])}</dd></div>' for key,label in
               (('generic','Generic'),('maker','Manufacturer'),('strength','Strength'),('form','Dosage form'),('pack','Pack size'),
                ('classification','Sale class'),('dar','DAR / MA')) if p[key])
    quantity=inp('quantity','Quantity of '+p['sale_unit'],1,'number',True,extra='min="1" max="10000"')
    totals=f'<p class="price">{money(p["price"])} <small>per {e(p["sale_unit"])}</small></p>'
    booking=form(r,'cart_add',hidden('id',p['id'])+quantity+button('Add to cart'),cls='inline')
    clinical=json.loads(p['clinical'])
    references=''
    if p['source_url']:
        references+=link(e(p['source_url']),'Source record ↗','text')
    if clinical.get('leaflet_url'):
        references+=link(e(clinical['leaflet_url']),'Prescribing leaflet ↗','text')
    if clinical.get('storage'):
        references+='<p><strong>Storage</strong> '+e(clinical['storage'])+'</p>'
    return card(product_label(p),f'<dl class="specs">{variant}</dl>{totals}{booking}'+('<div class="subpanel">'+references+'</div>' if references else ''),link(url(r,'/'),'Back to catalog','text'))

def cart_view(r):
    current=mode(r.setting)
    if current=='draft':
        return card('Online orders are paused','<p>Contact the pharmacy for service information.</p>')
    listing=[]
    total=0
    possible_rx=False
    for pid,qty in r.session.get('cart',{}).items():
        p=one(r.db,'SELECT * FROM products WHERE id=?',(pid,))
        if not p:
            continue
        possible_rx=possible_rx or p['classification']=='rx'
        total+=p['price']*qty
        quantity=f'<input type="number" class="quantity" name="qty_{p["id"]}" value="{int(qty)}" min="0" max="10000" aria-label="Quantity for {e(p["brand"])}">'
        listing.append((e(product_label(p)),e(p['sale_unit']),money(p['price']),quantity,money(p['price']*qty)))
    if not listing:
        return card('Your cart',f'<p class="empty">Add products to your cart before checkout.</p>{link(url(r,"/"),"Browse products","primary")}')+(
            f'<div id="prescription">{card("Prescription orders","<p>Add your prescribed products to the cart and attach the prescription at checkout. The pharmacist will verify your order before it can be dispatched.</p>")}</div>')
    basket=table(('Item','Unit','Price','Qty','Amount'),listing)+'<p class="muted">Set quantity to 0 to remove a product.</p>'+button('Update quantities','secondary')
    zones=rows(r.db,'SELECT z.* FROM zones z JOIN branches b ON b.id=z.branch_id WHERE z.active=1 AND b.active=1 ORDER BY z.name')
    phone=r.session.get('verified_mobile',{}).get('phone','') if current=='live' else ''
    fields=grid(inp('customer','Customer name',required=True)+inp('phone','Bangladesh mobile',phone,kind='tel',required=True,extra='placeholder="01XXXXXXXXX"')+
        select('zone','Delivery zone',[(z['id'],f'{z["name"]} · {money(z["fee"])} · {z["eta"]}') for z in zones])+
        select('customer_role','Ordering for',[('self','Myself'),('guardian','As legal guardian')])+select('payment','Payment',[('COD','Cash on delivery')]+([('SSLCommerz','Online payment via SSLCOMMERZ')] if current=='live' and gateway.configuration() else [])))
    if current=='live' and gateway.configuration():
        fields+=inp('email','Email for online payment',kind='email')
    fields+=textarea('address','Delivery address',required=True)+inp('rx','Prescription image or PDF'+(' (required)' if possible_rx else ' (if applicable)'),kind='file',required=possible_rx,extra='accept="application/pdf,image/jpeg,image/png"')
    fields+='<p class="muted">Your prescription is kept private and reviewed by authorised pharmacy staff.</p>'+button('Place order')
    verification=''
    if current=='live' and sms.configuration():
        verification=form(r,'otp_send',inp('verify_phone','Mobile number for SMS',phone,kind='tel',required=True,extra='autocomplete="tel"')+button('Send OTP','secondary'),cls='inline')
        if r.session.get('otp'):
            verification+=form(r,'otp_confirm',inp('otp_code','Six-digit code',kind='text',required=True,extra='inputmode="numeric" autocomplete="one-time-code" maxlength="6"')+button('Verify mobile'),cls='inline')
    if current=='live' and not sms.configuration():
        checkout='<div class="empty">Mobile verification is temporarily unavailable.</div>'
    elif zones:
        checkout=verification+form(r,'checkout',hidden('submission',secrets.token_hex(16))+fields,files=True,cls='stack')
    else:
        checkout='<div class="empty">Delivery is currently unavailable.</div>'
    return card('Your cart',form(r,'cart_update',basket,cls='stack')+f'<p class="price">Items subtotal {money(total)}</p>')+f'<div id="prescription">{card("Checkout",checkout)}</div>'

def track(r):
    code=r.query.get('code','')[:40]
    found=None
    if r.session.get('tracking'):
        found=one(r.db,'SELECT * FROM orders WHERE id=? AND code=?',(r.session['tracking'],code.upper()))
    if not found:
        return card('Track your order',form(r,'track',grid(inp('code','Order number',code,required=True)+inp('phone','Mobile used at checkout',kind='tel',required=True))+button('Find order'),cls='stack'))
    total=money(found['subtotal']+found['delivery'])
    details=f'<div class="order-meta">{order_badge(found["status"])}<b>{total}</b><span>Delivery estimate {e(found["eta"])}</span></div>'
    if found['payment']=='SSLCommerz':
        details+=f'<p>Payment {pill("Confirmed","green") if found["paid"] else pill("Awaiting payment","amber")}</p>'
        if not found['paid'] and found['status'] in ('Confirmed','Packing') and gateway.configuration() and mode(r.setting)=='live':
            details+=form(r,'pay',button('Continue to secure payment'))
    if found['tracking']:
        details+='<p>Courier tracking number '+e(found['tracking'])+'</p>'
    if found['review_note']:
        details+=f'<p>{e(found["review_note"])}</p>'
    tickets_found=rows(r.db,'SELECT status,resolution FROM tickets WHERE code=? ORDER BY id DESC',(found['code'],))
    complain=form(r,'complaint',hidden('code',found['code'])+hidden('phone',found['phone'])+textarea('body','Describe the issue',required=True)+button('Send complaint'),cls='stack')
    support=''.join(f'<div class="ticket-result">{pill(t["status"])} {e(t["resolution"])}</div>' for t in tickets_found)
    return card(found['code'],details)+card('Order support',complain+support)

def render_store(r):
    current=mode(r.setting)
    cart_size=sum(r.session.get('cart',{}).values())
    top='<div class="store-top">'+('Pilot store · training orders only' if current=='demo' else e(r.setting.get('hours') or 'Astha Pharmacy'))+'</div>'
    nav=f'<header class="store-header"><div class="store-shell storebar">{brand(r)}{search_form(r,"/",r.query.get("q","")[:160],category=r.query.get("category",""))}<nav>{link(url(r,"/track"),"Track order","text")}{link(url(r,"/cart"),f"Cart · {cart_size}","secondary")}</nav></div></header>'
    routes={'/':storefront,'/product':view_product,'/cart':cart_view,'/track':track,'/policy':lambda req:card('Return policy','<p>'+e(req.setting.get('return_policy') or 'Contact your pharmacy for its returns process.')+'</p>')}
    main=routes[r.route](r)
    footer=f'<footer class="store-footer"><div class="store-shell">{brand(r)}<span>Astha Pharmacy Soft by Zeekodes</span>{link(url(r,"/admin"),"Staff sign-in","text")}</div></footer>'
    return page(r,'Storefront',top+nav+f'<main class="store-shell store-main">{notice(r)}{main}{public_info(r)}</main>'+footer,'store')
