<?php
declare(strict_types=1);

function app_nav_icon(string $key): string {
    $paths=[
        'dashboard'=>'<rect x="3" y="3" width="7" height="7" rx="2"/><rect x="14" y="3" width="7" height="7" rx="2"/><rect x="3" y="14" width="7" height="7" rx="2"/><rect x="14" y="14" width="7" height="7" rx="2"/>',
        'crm'=>'<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/>',
        'whatsapp'=>'<path d="M21 11.5a8.4 8.4 0 0 1-9 8.4 8.8 8.8 0 0 1-3.8-.9L3 21l1.8-5a8.6 8.6 0 1 1 16.2-4.5z"/><path d="M8.8 8.3c.5 2.5 2.4 4.4 4.9 4.9M13.7 13.2l1.7-.8 1.2 1.2c-.5 1.5-1.8 2.2-3 1.8-3.3-1-5.9-3.6-6.9-6.9-.4-1.2.3-2.5 1.8-3l1.2 1.2-.8 1.6"/>',
        'operations'=>'<path d="M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4z"/><path d="M17 14v6M14 17h6"/>',
        'refills'=>'<path d="M20 7h-7V2M4 17h7v5"/><path d="M20.49 9A9 9 0 0 0 5.64 5.64L4 7m16 10-1.64 1.36A9 9 0 0 1 3.51 15"/>',
        'deliveries'=>'<path d="M10 17h4V5H2v12h3"/><path d="M14 9h4l4 4v4h-3"/><circle cx="7.5" cy="17.5" r="2.5"/><circle cx="16.5" cy="17.5" r="2.5"/>',
        'web-orders'=>'<path d="M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"/><path d="M3 6h18M16 10a4 4 0 0 1-8 0"/>',
        'quotations'=>'<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6M8 13h8M8 17h5"/>',
        'invoices'=>'<path d="M6 2h12a2 2 0 0 1 2 2v18l-4-2-4 2-4-2-4 2V4a2 2 0 0 1 2-2z"/><path d="M8 7h8M8 11h8M8 15h5"/>',
        'payments'=>'<rect x="2" y="5" width="20" height="14" rx="2"/><path d="M2 10h20M6 15h2"/>',
        'statement'=>'<path d="M4 6h16M4 12h16M4 18h10"/><circle cx="19" cy="18" r="2"/>',
        'customers'=>'<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>',
        'team'=>'<path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="8.5" cy="7" r="4"/><path d="M20 8v6M17 11h6"/>',
        'products'=>'<path d="m21 8-9-5-9 5 9 5 9-5z"/><path d="m3 8 9 5 9-5M3 12l9 5 9-5M3 16l9 5 9-5"/>',
        'expenses'=>'<path d="M12 2v14M7 11l5 5 5-5"/><path d="M5 22h14"/>',
        'suppliers'=>'<path d="M3 21h18M6 21V7l6-4 6 4v14M9 10h6M9 14h6M9 18h6"/>',
        'bills'=>'<path d="M9 2h6l1 3h4v17H4V5h4l1-3z"/><path d="M9 2v3h6V2M8 11h8M8 15h8"/>',
        'reports'=>'<path d="M4 20V10M10 20V4M16 20v-7M22 20H2"/>',
        'finance'=>'<path d="M3 6h18M5 6l7-4 7 4M5 10v8M9 10v8M15 10v8M19 10v8M3 22h18"/>',
        'imports'=>'<path d="M12 3v12M7 8l5-5 5 5"/><path d="M5 21h14a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2"/>',
        'profile'=>'<circle cx="12" cy="8" r="4"/><path d="M4 22a8 8 0 0 1 16 0"/><path d="M18 4l1-1M5 5 4 4"/>',
        'settings'=>'<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .34 1.88l.06.06-2.83 2.83-.06-.06A1.7 1.7 0 0 0 15 19.4a1.7 1.7 0 0 0-1 .6 1.7 1.7 0 0 0-.4 1v.1h-4v-.1a1.7 1.7 0 0 0-1.1-1.6 1.7 1.7 0 0 0-1.88.34l-.06.06-2.83-2.83.06-.06A1.7 1.7 0 0 0 4.6 15a1.7 1.7 0 0 0-.6-1 1.7 1.7 0 0 0-1-.4h-.1v-4H3A1.7 1.7 0 0 0 4.6 8.5a1.7 1.7 0 0 0-.34-1.88l-.06-.06 2.83-2.83.06.06A1.7 1.7 0 0 0 9 4.6a1.7 1.7 0 0 0 1-.6 1.7 1.7 0 0 0 .4-1v-.1h4V3a1.7 1.7 0 0 0 1.1 1.6 1.7 1.7 0 0 0 1.88-.34l.06-.06 2.83 2.83-.06.06A1.7 1.7 0 0 0 19.4 9c.17.38.4.72.6 1 .26.27.62.42 1 .4h.1v4H21a1.7 1.7 0 0 0-1.6.6z"/>',
    ];
    return '<svg viewBox="0 0 24 24" aria-hidden="true">'.($paths[$key]??$paths['dashboard']).'</svg>';
}

function render_header(string $title, string $active = 'dashboard'): void {
    $u=user();
    $flashes=take_flashes();
    $navCounts=[];
    try{
        $navCounts['invoices']=(int)db()->query('SELECT COUNT(*) FROM (SELECT d.id,'.finance_document_balance_sql('d').' balance FROM documents d WHERE d.type="invoice" AND d.status NOT IN ("cancelled","draft","paid") AND d.due_date<CURDATE() HAVING balance>.009) overdue_invoices')->fetchColumn();
        $navCounts['web-orders']=(int)db()->query('SELECT COUNT(*) FROM web_orders WHERE status="new"')->fetchColumn();
        $navCounts['refills']=(int)db()->query('SELECT COUNT(*) FROM refill_jobs WHERE status NOT IN ("completed","cancelled")')->fetchColumn();
        $navCounts['deliveries']=(int)db()->query('SELECT COUNT(*) FROM deliveries WHERE status NOT IN ("delivered","cancelled")')->fetchColumn();
        $navCounts['operations']=(int)db()->query('SELECT (SELECT COUNT(*) FROM refill_jobs WHERE status NOT IN ("completed","cancelled") AND due_at<NOW())+(SELECT COUNT(*) FROM deliveries WHERE status NOT IN ("delivered","cancelled") AND scheduled_for<NOW())')->fetchColumn();
        $navCounts['whatsapp']=(int)db()->query('SELECT COALESCE(SUM(unread_count),0) FROM whatsapp_conversations')->fetchColumn();
    }catch(Throwable $ignored){}
    $groups=[
        'Overview'=>['dashboard'=>['Business overview','D']],
        'Sales'=>[
            'web-orders'=>['Online orders','W'],
            'quotations'=>['Quotations','Q'],
            'invoices'=>['Invoices','I'],
            'payments'=>['Payments','$'],
            'statement'=>['Statements','T'],
        ],
        'Customers'=>[
            'customers'=>['Customer directory','C'],
            'crm'=>['Sales pipeline','R'],
            'whatsapp'=>['WhatsApp inbox','W'],
        ],
        'Fulfilment'=>[
            'operations'=>['Operations board','O'],
            'refills'=>['CO₂ refill jobs','G'],
            'deliveries'=>['Deliveries','V'],
        ],
        'Stock & purchasing'=>[
            'products'=>['Products & inventory','P'],
            'suppliers'=>['Suppliers','S'],
            'bills'=>['Bills & payables','B'],
            'expenses'=>['Expenses','E'],
        ],
        'Finance'=>[
            'finance'=>['Finance centre','F'],
            'reports'=>['Reports','R'],
        ],
        'Workspace'=>[
            'imports'=>['Data imports','U'],
            'team'=>['Team & access','T'],
            'profile'=>['My profile','M'],
            'settings'=>['Business settings','S'],
        ],
    ];
    $navPermissions=['web-orders'=>'website_orders.manage','customers'=>'customers.manage','crm'=>'crm.manage','whatsapp'=>'whatsapp.manage','operations'=>'operations.manage','refills'=>'operations.manage','deliveries'=>'operations.manage','products'=>'catalogue.manage','suppliers'=>'purchasing.manage','bills'=>'purchasing.manage','expenses'=>'expenses.manage','finance'=>'reports.view','reports'=>'reports.view','imports'=>'imports.manage','team'=>'users.manage','settings'=>'settings.manage'];
    ?><!doctype html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
        <meta name="robots" content="noindex,nofollow">
        <meta name="theme-color" content="#062b4d">
        <title><?=e($title)?> - Soda ZW Billing</title>
        <link rel="stylesheet" href="assets/accounting-os-v6.css?v=20260718-finance-control-v1">
        <link rel="stylesheet" href="assets/sodazw-v10.css?v=<?=e(BILLING_BUILD_ID)?>">
        <link rel="stylesheet" href="assets/sodazw-v12.css?v=<?=e(BILLING_BUILD_ID)?>">
        <link rel="stylesheet" href="assets/sodazw-invoice-classic.css?v=<?=e(BILLING_BUILD_ID)?>">
        <link rel="stylesheet" href="assets/sodazw-mobile.css?v=<?=e(BILLING_BUILD_ID)?>">
        <link rel="stylesheet" href="assets/sodazw-v14.css?v=<?=e(BILLING_BUILD_ID)?>">
    </head>
    <body class="accounting-v6 sodazw-v10 sodazw-v12 sodazw-v14 page-<?=e($active)?>">
    <a class="skip-link" href="#billing-main">Skip to main content</a>
    <div class="app-shell">
        <aside class="sidebar" id="primary-navigation" aria-label="Primary navigation">
            <div class="brand-row"><a class="brand" href="index.php"><img src="assets/sodazw-logo.png" alt="Soda ZW"><span><strong>Soda ZW</strong><small>Billing &amp; Operations</small></span></a><button class="sidebar-collapse" type="button" aria-label="Collapse navigation" aria-expanded="true">&lsaquo;</button></div>
            <nav aria-label="Accounting sections">
                <?php foreach($groups as $label=>$items):?>
                    <span class="nav-section"><?=e($label)?></span>
                    <?php foreach($items as $key=>$item):?>
                        <?php if(isset($navPermissions[$key])&&!has_permission($navPermissions[$key]))continue;?>
                        <a class="<?=$active===$key?'active':''?>" href="index.php?page=<?=$key?>" <?=$active===$key?'aria-current="page"':''?> aria-label="<?=e($item[0])?>"><b><?=app_nav_icon($key)?></b><span class="nav-label"><?=e($item[0])?></span><?php if(($navCounts[$key]??0)>0):?><em class="nav-count" aria-label="<?=e((string)$navCounts[$key])?> items"><?=e((string)$navCounts[$key])?></em><?php endif;?></a>
                    <?php endforeach;?>
                <?php endforeach;?>
            </nav>
            <div class="sidebar-user"><span class="user-avatar"><?=e(strtoupper(substr((string)$u['name'],0,1)))?></span><span class="user-copy"><strong><?=e($u['name'])?></strong><small><?=e(ucfirst($u['role']))?></small></span><form class="sidebar-logout-form" method="post" action="logout.php"><?=csrf_field()?><button class="sidebar-logout" type="submit" title="Log out of Soda ZW Billing" aria-label="Log out">Log out</button></form></div>
        </aside><button class="mobile-backdrop" type="button" aria-label="Close navigation" hidden></button>
        <main class="main" id="billing-main">
            <header class="topbar system-topbar"><button class="menu-toggle" aria-label="Open navigation" aria-controls="primary-navigation" aria-expanded="false">&#9776;</button><div class="page-identity"><span>Soda ZW &middot; Accounting &amp; operations</span><h1><?=e($title)?></h1></div><div class="topbar-tools"><a class="topbar-icon" href="index.php?page=whatsapp" title="WhatsApp inbox" aria-label="WhatsApp inbox"><?=app_nav_icon('whatsapp')?><?php if(($navCounts['whatsapp']??0)>0):?><i><?=e((string)$navCounts['whatsapp'])?></i><?php endif;?></a><details class="create-menu"><summary><span>+</span> Create</summary><div><a href="quick-invoice.php"><?=app_nav_icon('invoices')?><span><b>Invoice</b><small>Bill a customer</small></span></a><a href="receive-payment.php"><?=app_nav_icon('payments')?><span><b>Receive payment</b><small>Allocate a customer receipt</small></span></a><a href="quick-invoice.php?type=quotation"><?=app_nav_icon('quotations')?><span><b>Quotation</b><small>Prepare a price</small></span></a><a href="index.php?page=customers&edit=new"><?=app_nav_icon('customers')?><span><b>Customer</b><small>Add a contact</small></span></a><a href="index.php?page=expenses"><?=app_nav_icon('expenses')?><span><b>Expense</b><small>Record money spent</small></span></a><a href="index.php?page=refills&new=1"><?=app_nav_icon('refills')?><span><b>Refill job</b><small>Track a cylinder</small></span></a><a href="index.php?page=deliveries&new=1"><?=app_nav_icon('deliveries')?><span><b>Delivery</b><small>Schedule dispatch</small></span></a></div></details><a class="topbar-profile" href="index.php?page=profile"><span><?=e(strtoupper(substr((string)$u['name'],0,1)))?></span><b><?=e(explode(' ',trim((string)$u['name']))[0])?></b></a></div></header>
            <?php if(($u['role']??'')==='owner' && !billing_schema_is_current()):?><div class="alert error" role="alert"><strong>Database upgrade required.</strong> Normal pages are no longer allowed to change the schema. <a href="upgrade.php">Run the controlled owner upgrade</a>.</div><?php endif;?>
            <?php foreach($flashes as $flash):?><div class="alert <?=e($flash['type'])?>" role="<?=$flash['type']==='error'?'alert':'status'?>" aria-live="<?=$flash['type']==='error'?'assertive':'polite'?>"><?=e($flash['message'])?></div><?php endforeach;?>
    <?php
}

function render_footer(): void {
    ?><footer class="app-footer">Soda ZW Billing &amp; Operations &middot; Secure private workspace &middot; Build <?=e(BILLING_BUILD_ID)?></footer></main></div><script src="assets/app.js?v=<?=e(BILLING_BUILD_ID)?>"></script></body></html><?php
}

function status_badge(string $status): string {
    $safeClass = preg_replace('/[^a-z0-9_-]/i', '', $status) ?: 'unknown';
    $label = ucwords(str_replace('_', ' ', $status));
    return '<span class="status status-' . e($safeClass) . '">' . e($label) . '</span>';
}
