<?php
/* ============================================================================
   WBMCZ ADMIN — ORDERS, COLLECTIONS & SELLER DUES
   ----------------------------------------------------------------------------
   Three tabs, one question each:

     Orders        which orders still have money outstanding, and where are they
     Collections   what have sellers reported taking, and is it right
     Seller Dues   who is holding our money, and how much

   Nothing here moves money on its own. A collection only counts once it is
   verified, and a handover is only recorded when somebody says it happened.
   ============================================================================ */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/Language.php';
require_once __DIR__ . '/../includes/rbac.php';
require_once __DIR__ . '/../includes/shares.php';
require_once __DIR__ . '/../includes/wallet.php';
require_once __DIR__ . '/../includes/purchase.php';

if (!isLoggedIn() || !isAdmin()) { redirect('login.php'); }
rbac_guard(['manage_orders', 'manage_settings']);

$lang         = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id      = (int)$_SESSION['user_id'];
$company_name = getSetting('site_name', 'WBMCZ');

buy_ensure_schema($db);

$flash_ok  = $_SESSION['flash_success'] ?? ''; unset($_SESSION['flash_success']);
$flash_err = $_SESSION['flash_error']   ?? ''; unset($_SESSION['flash_error']);

/* ---------------------------------------------------------------------------
   ACTIONS
   --------------------------------------------------------------------------- */
$back = 'order_manage.php' . (!empty($_POST['back']) ? $_POST['back'] : '');

if (isset($_POST['approve_collection'])) {
    $r = buy_approve_collection($db, (int)$_POST['collection_id'], trim((string)($_POST['note'] ?? '')));
    if (!empty($r['ok'])) { $_SESSION['flash_success'] = 'Verified. The order has been updated.'; }
    else { $_SESSION['flash_error'] = $r['error'] ?? 'Could not verify that entry.'; }
    redirect($back);
}

if (isset($_POST['reject_collection'])) {
    $r = buy_reject_collection($db, (int)$_POST['collection_id'], trim((string)($_POST['reason'] ?? '')));
    if (!empty($r['ok'])) { $_SESSION['flash_success'] = 'Marked as rejected.'; }
    else { $_SESSION['flash_error'] = $r['error'] ?? 'Could not save that.'; }
    redirect($back);
}

/* the office takes a payment itself — online, or over the counter */
if (isset($_POST['office_payment'])) {
    $r = buy_record_collection($db, (int)$_POST['order_id'], [
        'amount'    => (float)($_POST['amount'] ?? 0),
        'mode'      => (string)($_POST['mode'] ?? 'company'),
        'reference' => trim((string)($_POST['reference'] ?? '')),
        'note'      => trim((string)($_POST['note'] ?? '')) ?: 'Recorded by the office',
        'seller_id' => (int)($_POST['seller_id'] ?? 0),
        'auto'      => true,
    ]);
    if (!empty($r['ok'])) { $_SESSION['flash_success'] = 'Payment recorded against the order.'; }
    else { $_SESSION['flash_error'] = $r['error'] ?? 'Could not record it.'; }
    redirect($back);
}

/* a seller hands cash in, or the company pays a seller out */
if (isset($_POST['settle'])) {
    $r = buy_settle($db, (int)$_POST['seller_id'], (float)($_POST['amount'] ?? 0),
        (string)($_POST['direction'] ?? 'in'), [
            'mode'      => (string)($_POST['mode'] ?? 'cash'),
            'reference' => trim((string)($_POST['reference'] ?? '')),
            'note'      => trim((string)($_POST['note'] ?? '')),
        ]);
    if (!empty($r['ok'])) {
        $_SESSION['flash_success'] = 'Recorded. That seller is now holding ₹' . number_format($r['holding'], 2) . '.';
    } else { $_SESSION['flash_error'] = $r['error'] ?? 'Could not record it.'; }
    redirect($back);
}

if (isset($_POST['assign_seller'])) {
    $r = buy_assign_seller($db, (int)$_POST['order_id'], (int)$_POST['new_seller_id'], 'Assigned from the office');
    $_SESSION[!empty($r['ok']) ? 'flash_success' : 'flash_error'] = !empty($r['ok']) ? 'Seller assigned.' : ($r['error'] ?? 'Could not assign.');
    redirect($back);
}

if (isset($_POST['complete_order'])) {
    $r = buy_complete_order($db, (int)$_POST['order_id'], 'Closed from the office');
    $_SESSION[!empty($r['ok']) ? 'flash_success' : 'flash_error'] = !empty($r['ok'])
        ? 'Order completed' . (!empty($r['released']) ? ' — ' . (int)$r['released'] . ' earning(s) released.' : '.')
        : ($r['error'] ?? 'Could not complete it.');
    redirect($back);
}

if (isset($_POST['cancel_order'])) {
    $r = buy_cancel_order($db, (int)$_POST['order_id'], trim((string)($_POST['reason'] ?? '')), !empty($_POST['refund']));
    $_SESSION[!empty($r['ok']) ? 'flash_success' : 'flash_error'] = !empty($r['ok'])
        ? 'Order cancelled' . (!empty($r['refunded']) ? ' and ₹' . number_format($r['refunded'], 2) . ' refunded to the wallet.' : '.')
        : ($r['error'] ?? 'Could not cancel it.');
    redirect($back);
}

/* ---------------------------------------------------------------------------
   WHAT THE PAGE SHOWS
   --------------------------------------------------------------------------- */
$tab = (string)($_GET['tab'] ?? 'orders');
if (!in_array($tab, ['orders', 'collections', 'dues'], true)) { $tab = 'orders'; }

$q      = trim((string)($_GET['q'] ?? ''));
$fstage = (string)($_GET['stage'] ?? '');
$fdue   = isset($_GET['due']) ? 1 : 0;
$page   = max(1, (int)($_GET['p'] ?? 1));
$per    = 25;

$orders = buy_orders($db, ['q' => $q, 'stage' => $fstage, 'due' => $fdue,
                           'limit' => $per, 'offset' => ($page - 1) * $per]);
$ototal = buy_orders_count($db, ['q' => $q, 'stage' => $fstage, 'due' => $fdue]);

$cstatus = (string)($_GET['cs'] ?? 'pending');
if (!in_array($cstatus, ['pending', 'approved', 'rejected', ''], true)) { $cstatus = 'pending'; }
$cols    = buy_collections($db, ['status' => $cstatus, 'q' => $q, 'limit' => 100]);

$dues = buy_seller_dues_list($db, ['q' => $q, 'only_due' => isset($_GET['only_due'])]);

/* headline numbers */
$stats = buy_stats($db);
$pending_count = 0; $pending_sum = 0.0;
try {
    $r = $db->select("SELECT COUNT(*) n, COALESCE(SUM(amount),0) s FROM seller_collections WHERE status = 'pending'");
    $pending_count = (int)($r[0]['n'] ?? 0);
    $pending_sum   = (float)($r[0]['s'] ?? 0);
} catch (\Throwable $e) {}
$held = 0.0; foreach ($dues as $d) { $held += $d['holding']; }

$sellers = [];
try { $sellers = $db->select("SELECT id, name, mobile FROM users WHERE user_type = 'seller' ORDER BY name ASC"); }
catch (\Throwable $e) {}

$qs = function ($over = []) use ($tab, $q, $fstage, $fdue, $cstatus, $page) {
    $a = array_merge(['tab' => $tab, 'q' => $q, 'stage' => $fstage, 'cs' => $cstatus, 'p' => $page], $over);
    if ($fdue) { $a['due'] = 1; }
    foreach ($a as $k => $v) { if ($v === '' || $v === null) { unset($a[$k]); } }
    return 'order_manage.php?' . http_build_query($a);
};
$backq = '?' . http_build_query(array_filter(['tab' => $tab, 'q' => $q, 'stage' => $fstage, 'cs' => $cstatus, 'p' => $page]));

function pr($n) { return '₹' . number_format((float)$n, 2); }
function dt($s) { return $s ? date('d M Y, g:i A', strtotime($s)) : '—'; }
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Order Management - <?php echo htmlspecialchars($company_name); ?> Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <style>
        body { font-family:'Inter',sans-serif; }
        [x-cloak] { display:none !important; }
        .lbl { display:block; font-size:11px; font-weight:700; color:#475569; margin-bottom:4px; }
        .fld { width:100%; border:1px solid #cbd5e1; border-radius:10px; padding:8px 11px; font-size:13px; background:#fff; }
        .fld:focus { outline:none; border-color:#6366f1; box-shadow:0 0 0 3px rgba(99,102,241,.15); }
        .kpi { background:#fff; border:1px solid #e5e7eb; border-radius:16px; padding:16px; }
        .tabbtn { padding:9px 16px; border-radius:12px; font-size:12.5px; font-weight:800; white-space:nowrap; }
        .tabbtn.on { background:#111827; color:#fff; }
        .tabbtn.off { background:#fff; color:#64748b; border:1px solid #e5e7eb; }
        .tag { display:inline-flex; align-items:center; gap:5px; padding:3px 9px; border-radius:999px; font-size:10.5px; font-weight:800; }
        .t-amber { background:#fffbeb; color:#b45309; border:1px solid #fde68a; }
        .t-green { background:#ecfdf5; color:#047857; border:1px solid #a7f3d0; }
        .t-red   { background:#fef2f2; color:#b91c1c; border:1px solid #fecaca; }
        .t-slate { background:#f1f5f9; color:#475569; border:1px solid #e2e8f0; }
        .t-indigo{ background:#eef2ff; color:#4338ca; border:1px solid #c7d2fe; }
        table.grid { width:100%; border-collapse:collapse; font-size:12.5px; }
        table.grid th { text-align:left; padding:10px 12px; background:#f8fafc; color:#64748b;
                        font-size:10.5px; font-weight:800; text-transform:uppercase; letter-spacing:.05em;
                        border-bottom:1px solid #e5e7eb; white-space:nowrap; }
        table.grid td { padding:11px 12px; border-bottom:1px solid #f1f5f9; vertical-align:top; }
        table.grid tr:hover td { background:#fafbfc; }
        .mini { padding:5px 10px; border-radius:9px; font-size:11px; font-weight:800; white-space:nowrap; }
    </style>
</head>
<body class="bg-gray-50" x-data="omBoard()" x-cloak>

<div class="flex h-screen overflow-hidden">
    <?php include __DIR__ . '/includes/sidebar.php'; ?>

    <div class="flex-1 flex flex-col min-w-0 bg-gray-100 overflow-hidden">

        <header class="h-20 bg-white text-slate-800 flex items-center justify-between px-4 lg:px-8 shadow-sm border-b border-gray-200 z-40 relative flex-shrink-0">
            <div class="flex items-center min-w-0">
                <button @click="sidebarOpen = !sidebarOpen" class="p-2 mr-3 text-slate-500 hover:text-indigo-600 rounded-lg hover:bg-gray-100"><i class="fas fa-bars text-xl"></i></button>
                <div class="min-w-0">
                    <h2 class="text-xl font-bold truncate">Order Management</h2>
                    <p class="text-[11px] text-slate-400 hidden sm:block">Visits, collections, and what each seller is holding</p>
                </div>
            </div>
            <?php if ($pending_count > 0): ?>
                <a href="<?php echo $qs(['tab' => 'collections', 'cs' => 'pending', 'p' => 1]); ?>"
                   class="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-amber-500 text-white text-xs font-bold shadow hover:bg-amber-600">
                    <i class="fas fa-clock"></i> <?php echo $pending_count; ?> waiting to verify
                </a>
            <?php endif; ?>
        </header>

        <main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8">

            <?php if ($flash_ok): ?>
                <div class="mb-5 bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-xl text-sm"><i class="fas fa-check-circle mr-2"></i><?php echo htmlspecialchars($flash_ok); ?></div>
            <?php endif; ?>
            <?php if ($flash_err): ?>
                <div class="mb-5 bg-rose-50 border border-rose-200 text-rose-700 px-4 py-3 rounded-xl text-sm"><i class="fas fa-circle-exclamation mr-2"></i><?php echo htmlspecialchars($flash_err); ?></div>
            <?php endif; ?>

            <!-- headline numbers -->
            <div class="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-5">
                <div class="kpi">
                    <p class="text-[10.5px] font-extrabold uppercase tracking-wider text-slate-400">Still to collect</p>
                    <p class="text-2xl font-extrabold text-amber-600 mt-1"><?php echo pr($stats['due']); ?></p>
                    <p class="text-[11px] text-slate-400"><?php echo (int)$stats['pending_visits']; ?> visit(s) outstanding</p>
                </div>
                <div class="kpi">
                    <p class="text-[10.5px] font-extrabold uppercase tracking-wider text-slate-400">Waiting to verify</p>
                    <p class="text-2xl font-extrabold text-indigo-600 mt-1"><?php echo pr($pending_sum); ?></p>
                    <p class="text-[11px] text-slate-400"><?php echo $pending_count; ?> report(s) from sellers</p>
                </div>
                <div class="kpi">
                    <p class="text-[10.5px] font-extrabold uppercase tracking-wider text-slate-400">Held by sellers</p>
                    <p class="text-2xl font-extrabold text-rose-600 mt-1"><?php echo pr($held); ?></p>
                    <p class="text-[11px] text-slate-400">verified, not handed in yet</p>
                </div>
                <div class="kpi">
                    <p class="text-[10.5px] font-extrabold uppercase tracking-wider text-slate-400">Collected in all</p>
                    <p class="text-2xl font-extrabold text-emerald-600 mt-1"><?php echo pr($stats['collected']); ?></p>
                    <p class="text-[11px] text-slate-400"><?php echo (int)$stats['completed']; ?> order(s) completed</p>
                </div>
            </div>

            <!-- tabs + search -->
            <div class="flex flex-wrap items-center gap-2 mb-4">
                <a href="<?php echo $qs(['tab' => 'orders', 'p' => 1]); ?>"      class="tabbtn <?php echo $tab === 'orders' ? 'on' : 'off'; ?>"><i class="fas fa-box mr-1"></i> Orders</a>
                <a href="<?php echo $qs(['tab' => 'collections', 'p' => 1]); ?>" class="tabbtn <?php echo $tab === 'collections' ? 'on' : 'off'; ?>"><i class="fas fa-sack-dollar mr-1"></i> Collections<?php if ($pending_count): ?> (<?php echo $pending_count; ?>)<?php endif; ?></a>
                <a href="<?php echo $qs(['tab' => 'dues', 'p' => 1]); ?>"        class="tabbtn <?php echo $tab === 'dues' ? 'on' : 'off'; ?>"><i class="fas fa-scale-balanced mr-1"></i> Seller Dues</a>

                <form method="GET" class="ml-auto flex items-center gap-2">
                    <input type="hidden" name="tab" value="<?php echo htmlspecialchars($tab); ?>">
                    <input type="hidden" name="cs" value="<?php echo htmlspecialchars($cstatus); ?>">
                    <input name="q" value="<?php echo htmlspecialchars($q); ?>" placeholder="Order code, customer, seller…"
                           class="fld" style="width:250px">
                    <?php if ($tab === 'orders'): ?>
                        <label class="flex items-center gap-1.5 text-[12px] font-bold text-slate-600 whitespace-nowrap">
                            <input type="checkbox" name="due" value="1" <?php echo $fdue ? 'checked' : ''; ?> class="accent-indigo-600"> Only with money due
                        </label>
                    <?php endif; ?>
                    <button class="mini bg-slate-900 text-white"><i class="fas fa-magnifying-glass"></i></button>
                </form>
            </div>

            <?php if ($tab === 'orders'): ?>
            <!-- ================= ORDERS ================= -->
            <div class="bg-white rounded-2xl border border-gray-200 overflow-hidden">
                <div class="overflow-x-auto">
                <table class="grid">
                    <thead><tr>
                        <th>Order</th><th>Customer</th><th>Seller</th><th>Money</th><th>Stage</th><th class="text-right">Do</th>
                    </tr></thead>
                    <tbody>
                    <?php if (empty($orders)): ?>
                        <tr><td colspan="6" class="p-12 text-center text-slate-400">No orders match that.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($orders as $o): $due = (float)$o['due_amount']; ?>
                    <tr>
                        <td>
                            <a href="../order.php?id=<?php echo (int)$o['id']; ?>" class="font-extrabold text-indigo-700 hover:underline"><?php echo htmlspecialchars($o['order_code'] ?: ('#' . $o['id'])); ?></a>
                            <p class="text-slate-500 mt-0.5"><?php echo htmlspecialchars($o['service_name']); ?></p>
                            <p class="text-[11px] text-slate-400 mt-0.5"><?php echo dt($o['created_at']); ?></p>
                            <?php if ((string)$o['fulfilment'] === 'visit'): ?><span class="tag t-amber mt-1"><i class="fas fa-person-walking"></i> Visit</span><?php endif; ?>
                            <?php if (!empty($o['payment_code']) && (string)$o['payment_code_status'] === 'pending'): ?>
                                <span class="tag t-indigo mt-1"><i class="fas fa-barcode"></i> <?php echo htmlspecialchars($o['payment_code']); ?></span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <p class="font-bold text-slate-700"><?php echo htmlspecialchars($o['customer_name'] ?: '—'); ?></p>
                            <p class="text-slate-500"><?php echo htmlspecialchars($o['customer_mobile'] ?: ''); ?></p>
                            <?php if (!empty($o['address'])): ?>
                                <p class="text-[11px] text-slate-400 mt-0.5 max-w-[220px]"><?php echo htmlspecialchars($o['address']); ?></p>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php
                            $sn = '';
                            if (!empty($o['seller_id'])) {
                                foreach ($sellers as $s) { if ((int)$s['id'] === (int)$o['seller_id']) { $sn = $s['name']; break; } }
                                if ($sn === '') { $sn = 'Seller #' . (int)$o['seller_id']; }
                            }
                            ?>
                            <?php if ($sn !== ''): ?>
                                <p class="font-bold text-slate-700"><?php echo htmlspecialchars($sn); ?></p>
                            <?php else: ?>
                                <span class="tag t-red">Nobody yet</span>
                            <?php endif; ?>
                            <button @click="assign(<?php echo (int)$o['id']; ?>, '<?php echo htmlspecialchars(addslashes($o['order_code']), ENT_QUOTES); ?>')"
                                    class="text-[11px] font-bold text-indigo-600 hover:underline mt-1">Change</button>
                        </td>
                        <td>
                            <p class="font-extrabold text-slate-800"><?php echo pr($o['amount']); ?></p>
                            <p class="text-[11px] text-emerald-600 font-bold">Paid <?php echo pr($o['paid_amount']); ?></p>
                            <?php if ($due > 0): ?>
                                <p class="text-[11px] text-amber-700 font-bold">Due <?php echo pr($due); ?></p>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php $m = buy_stage_meta($o['stage']); ?>
                            <span class="tag <?php echo (string)$o['stage'] === 'completed' ? 't-green' : ((string)$o['stage'] === 'cancelled' ? 't-red' : 't-slate'); ?>">
                                <i class="fas <?php echo $m[1]; ?>"></i> <?php echo htmlspecialchars($m[0]); ?>
                            </span>
                        </td>
                        <td class="text-right whitespace-nowrap">
                            <?php if ($due > 0 && (string)$o['stage'] !== 'cancelled'): ?>
                                <button @click="takeMoney(<?php echo (int)$o['id']; ?>, '<?php echo htmlspecialchars(addslashes($o['order_code']), ENT_QUOTES); ?>', <?php echo $due; ?>, <?php echo (int)$o['seller_id']; ?>)"
                                        class="mini bg-emerald-600 text-white hover:bg-emerald-700"><i class="fas fa-indian-rupee-sign"></i> Take payment</button>
                            <?php elseif ((string)$o['stage'] !== 'completed' && (string)$o['stage'] !== 'cancelled'): ?>
                                <form method="POST" class="inline" onsubmit="return confirm('Close this order and release the seller\'s earning?');">
                                    <input type="hidden" name="order_id" value="<?php echo (int)$o['id']; ?>">
                                    <input type="hidden" name="back" value="<?php echo htmlspecialchars($backq); ?>">
                                    <button name="complete_order" value="1" class="mini bg-slate-900 text-white hover:bg-slate-700"><i class="fas fa-flag-checkered"></i> Complete</button>
                                </form>
                            <?php endif; ?>
                            <?php if ((string)$o['stage'] !== 'cancelled' && (string)$o['stage'] !== 'completed'): ?>
                                <button @click="cancel(<?php echo (int)$o['id']; ?>, '<?php echo htmlspecialchars(addslashes($o['order_code']), ENT_QUOTES); ?>')"
                                        class="mini bg-white text-rose-600 border border-rose-200 hover:bg-rose-50 mt-1"><i class="fas fa-ban"></i></button>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
                </div>
                <?php $pages = max(1, (int)ceil($ototal / $per)); if ($pages > 1): ?>
                <div class="flex items-center justify-between px-4 py-3 border-t border-gray-100">
                    <p class="text-[12px] text-slate-500"><?php echo $ototal; ?> order(s) · page <?php echo $page; ?> of <?php echo $pages; ?></p>
                    <div class="flex gap-1.5">
                        <?php if ($page > 1): ?><a href="<?php echo $qs(['p' => $page - 1]); ?>" class="mini bg-white border border-gray-200">Previous</a><?php endif; ?>
                        <?php if ($page < $pages): ?><a href="<?php echo $qs(['p' => $page + 1]); ?>" class="mini bg-white border border-gray-200">Next</a><?php endif; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <?php if ($tab === 'collections'): ?>
            <!-- ================= COLLECTIONS ================= -->
            <div class="flex gap-2 mb-3">
                <?php foreach (['pending' => 'Waiting', 'approved' => 'Verified', 'rejected' => 'Rejected', '' => 'Everything'] as $k => $lb): ?>
                    <a href="<?php echo $qs(['cs' => $k]); ?>" class="mini <?php echo $cstatus === $k ? 'bg-slate-900 text-white' : 'bg-white text-slate-600 border border-gray-200'; ?>"><?php echo $lb; ?></a>
                <?php endforeach; ?>
            </div>

            <div class="bg-white rounded-2xl border border-gray-200 overflow-hidden">
                <div class="overflow-x-auto">
                <table class="grid">
                    <thead><tr>
                        <th>Order</th><th>Seller</th><th>Amount</th><th>How</th><th>Reported</th><th class="text-right">Do</th>
                    </tr></thead>
                    <tbody>
                    <?php if (empty($cols)): ?>
                        <tr><td colspan="6" class="p-12 text-center text-slate-400">
                            <?php echo $cstatus === 'pending' ? 'Nothing is waiting to be verified.' : 'Nothing here.'; ?>
                        </td></tr>
                    <?php endif; ?>
                    <?php foreach ($cols as $c): ?>
                    <tr>
                        <td>
                            <a href="../order.php?id=<?php echo (int)$c['order_id']; ?>" class="font-extrabold text-indigo-700 hover:underline"><?php echo htmlspecialchars($c['order_code'] ?: ('#' . $c['order_id'])); ?></a>
                            <p class="text-slate-500 mt-0.5"><?php echo htmlspecialchars($c['service_name'] ?: ''); ?></p>
                            <p class="text-[11px] text-slate-400"><?php echo htmlspecialchars($c['customer_name'] ?: ''); ?></p>
                        </td>
                        <td>
                            <p class="font-bold text-slate-700"><?php echo htmlspecialchars($c['seller_name'] ?: ('Seller #' . $c['seller_id'])); ?></p>
                            <p class="text-slate-500"><?php echo htmlspecialchars($c['seller_mobile'] ?: ''); ?></p>
                        </td>
                        <td><p class="font-extrabold text-slate-800"><?php echo pr($c['amount']); ?></p></td>
                        <td>
                            <span class="tag <?php echo buy_mode_holds($c['mode']) ? 't-amber' : 't-green'; ?>"><?php echo htmlspecialchars(buy_mode_label($c['mode'])); ?></span>
                            <?php if (!empty($c['reference'])): ?><p class="text-[11px] text-slate-400 mt-1"><?php echo htmlspecialchars($c['reference']); ?></p><?php endif; ?>
                            <?php if (!empty($c['note'])): ?><p class="text-[11px] text-slate-400 mt-0.5 max-w-[200px]"><?php echo htmlspecialchars($c['note']); ?></p><?php endif; ?>
                        </td>
                        <td>
                            <p class="text-slate-600"><?php echo dt($c['created_at']); ?></p>
                            <p class="text-[11px] text-slate-400"><?php echo htmlspecialchars($c['recorded_by_name'] ?: ''); ?></p>
                            <?php if ($c['status'] !== 'pending'): ?>
                                <span class="tag <?php echo $c['status'] === 'approved' ? 't-green' : 't-red'; ?> mt-1"><?php echo ucfirst($c['status']); ?></span>
                                <p class="text-[11px] text-slate-400 mt-0.5"><?php echo htmlspecialchars($c['approved_by_name'] ?: ''); ?> · <?php echo dt($c['approved_at']); ?></p>
                            <?php endif; ?>
                        </td>
                        <td class="text-right whitespace-nowrap">
                            <?php if ($c['status'] === 'pending'): ?>
                                <form method="POST" class="inline">
                                    <input type="hidden" name="collection_id" value="<?php echo (int)$c['id']; ?>">
                                    <input type="hidden" name="back" value="<?php echo htmlspecialchars($backq); ?>">
                                    <button name="approve_collection" value="1" class="mini bg-emerald-600 text-white hover:bg-emerald-700"><i class="fas fa-check"></i> Verify</button>
                                </form>
                                <button @click="reject(<?php echo (int)$c['id']; ?>, <?php echo (float)$c['amount']; ?>)"
                                        class="mini bg-white text-rose-600 border border-rose-200 hover:bg-rose-50"><i class="fas fa-xmark"></i></button>
                            <?php else: ?>
                                <span class="text-[11px] text-slate-300">—</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
                </div>
            </div>
            <?php endif; ?>

            <?php if ($tab === 'dues'): ?>
            <!-- ================= SELLER DUES ================= -->
            <div class="flex items-center gap-2 mb-3">
                <a href="<?php echo $qs(['only_due' => null]); ?>" class="mini <?php echo isset($_GET['only_due']) ? 'bg-white text-slate-600 border border-gray-200' : 'bg-slate-900 text-white'; ?>">Everybody</a>
                <a href="<?php echo $qs() . '&only_due=1'; ?>" class="mini <?php echo isset($_GET['only_due']) ? 'bg-slate-900 text-white' : 'bg-white text-slate-600 border border-gray-200'; ?>">Only who owes</a>
            </div>

            <div class="bg-white rounded-2xl border border-gray-200 overflow-hidden">
                <div class="overflow-x-auto">
                <table class="grid">
                    <thead><tr>
                        <th>Seller</th><th>Collected for us</th><th>Handed in</th><th>Paid out to them</th>
                        <th>Holding now</th><th>Waiting to verify</th><th class="text-right">Do</th>
                    </tr></thead>
                    <tbody>
                    <?php if (empty($dues)): ?>
                        <tr><td colspan="7" class="p-12 text-center text-slate-400">Nobody has collected anything yet.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($dues as $d): ?>
                    <tr>
                        <td>
                            <p class="font-bold text-slate-800"><?php echo htmlspecialchars($d['name']); ?></p>
                            <p class="text-slate-500"><?php echo htmlspecialchars($d['mobile'] ?? ''); ?></p>
                            <p class="text-[11px] text-slate-400"><?php echo htmlspecialchars($d['user_code'] ?? ''); ?> · <?php echo (int)$d['orders']; ?> order(s)</p>
                        </td>
                        <td class="font-bold text-slate-700"><?php echo pr($d['collected']); ?></td>
                        <td class="font-bold text-emerald-600"><?php echo pr($d['handed_in']); ?></td>
                        <td class="font-bold text-indigo-600"><?php echo pr($d['paid_out']); ?></td>
                        <td>
                            <p class="text-lg font-extrabold <?php echo $d['holding'] > 0 ? 'text-rose-600' : 'text-slate-400'; ?>"><?php echo pr($d['holding']); ?></p>
                        </td>
                        <td>
                            <?php if ($d['pending'] > 0): ?>
                                <span class="tag t-amber"><?php echo pr($d['pending']); ?></span>
                            <?php else: ?><span class="text-slate-300">—</span><?php endif; ?>
                        </td>
                        <td class="text-right whitespace-nowrap">
                            <?php if ($d['holding'] > 0): ?>
                                <button @click="settle(<?php echo (int)$d['seller_id']; ?>, '<?php echo htmlspecialchars(addslashes($d['name']), ENT_QUOTES); ?>', <?php echo $d['holding']; ?>, 'in')"
                                        class="mini bg-emerald-600 text-white hover:bg-emerald-700"><i class="fas fa-hand-holding-dollar"></i> Cash received</button>
                            <?php endif; ?>
                            <button @click="settle(<?php echo (int)$d['seller_id']; ?>, '<?php echo htmlspecialchars(addslashes($d['name']), ENT_QUOTES); ?>', 0, 'out')"
                                    class="mini bg-white text-indigo-600 border border-indigo-200 hover:bg-indigo-50 mt-1"><i class="fas fa-arrow-up-from-bracket"></i> Pay them</button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
                </div>
            </div>

            <p class="text-[12px] text-slate-400 mt-3 leading-relaxed max-w-3xl">
                <b>Holding now</b> is verified cash and seller-side online collections, less what they have handed in, plus
                anything the company has paid them. It is company money in their hands — separate from their earnings, which
                reach their wallet through the usual share release when an order completes.
            </p>
            <?php endif; ?>

        </main>
    </div>
</div>

<!-- ===================== MODALS ===================== -->

<!-- take a payment against an order -->
<div x-show="box === 'money'" x-transition.opacity style="display:none" class="fixed inset-0 z-[110] flex items-center justify-center p-4">
    <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="box = null"></div>
    <div class="relative w-full max-w-md bg-white rounded-2xl shadow-2xl overflow-hidden">
        <div class="bg-gradient-to-r from-emerald-600 to-teal-600 px-5 py-4">
            <h3 class="text-white font-bold">Record a payment</h3>
            <p class="text-emerald-50 text-[12px]" x-text="'Order ' + cur.code"></p>
        </div>
        <form method="POST" class="p-5 space-y-3">
            <input type="hidden" name="order_id"  :value="cur.id">
            <input type="hidden" name="seller_id" :value="cur.seller">
            <input type="hidden" name="back" value="<?php echo htmlspecialchars($backq); ?>">
            <div>
                <label class="lbl">Amount</label>
                <input type="number" step="0.01" min="0.01" name="amount" class="fld" :max="cur.due" :value="cur.due" required>
                <p class="text-[11px] text-slate-400 mt-1" x-text="'Outstanding: ₹' + Number(cur.due).toFixed(2)"></p>
            </div>
            <div>
                <label class="lbl">How did it reach us?</label>
                <select name="mode" class="fld">
                    <?php foreach (buy_collection_modes() as $k => $m): ?>
                        <option value="<?php echo $k; ?>" <?php echo $k === 'company' ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($m[0]); ?> — <?php echo htmlspecialchars($m[3]); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <p class="text-[11px] text-slate-400 mt-1">Pick "Paid to company" for anything that reached our own account — it never lands on the seller's dues.</p>
            </div>
            <div>
                <label class="lbl">Reference</label>
                <input name="reference" class="fld" maxlength="120" placeholder="UPI id, receipt number, payment id…">
            </div>
            <div>
                <label class="lbl">Note</label>
                <input name="note" class="fld" maxlength="200">
            </div>
            <div class="flex justify-end gap-2 pt-1">
                <button type="button" @click="box = null" class="px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-100 rounded-lg">Cancel</button>
                <button name="office_payment" value="1" class="px-5 py-2 text-sm font-bold text-white bg-emerald-600 hover:bg-emerald-700 rounded-lg shadow">Record it</button>
            </div>
        </form>
    </div>
</div>

<!-- reject a collection -->
<div x-show="box === 'reject'" x-transition.opacity style="display:none" class="fixed inset-0 z-[110] flex items-center justify-center p-4">
    <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="box = null"></div>
    <div class="relative w-full max-w-md bg-white rounded-2xl shadow-2xl overflow-hidden">
        <div class="bg-gradient-to-r from-rose-500 to-red-600 px-5 py-4">
            <h3 class="text-white font-bold">Reject this report</h3>
            <p class="text-rose-50 text-[12px]" x-text="'₹' + Number(cur.amount).toFixed(2) + ' will not count against the order.'"></p>
        </div>
        <form method="POST" class="p-5 space-y-3">
            <input type="hidden" name="collection_id" :value="cur.id">
            <input type="hidden" name="back" value="<?php echo htmlspecialchars($backq); ?>">
            <div>
                <label class="lbl">Why?</label>
                <input name="reason" class="fld" maxlength="200" placeholder="The seller will see this" required>
            </div>
            <div class="flex justify-end gap-2">
                <button type="button" @click="box = null" class="px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-100 rounded-lg">Cancel</button>
                <button name="reject_collection" value="1" class="px-5 py-2 text-sm font-bold text-white bg-rose-600 hover:bg-rose-700 rounded-lg shadow">Reject</button>
            </div>
        </form>
    </div>
</div>

<!-- money changing hands with a seller -->
<div x-show="box === 'settle'" x-transition.opacity style="display:none" class="fixed inset-0 z-[110] flex items-center justify-center p-4">
    <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="box = null"></div>
    <div class="relative w-full max-w-md bg-white rounded-2xl shadow-2xl overflow-hidden">
        <div class="px-5 py-4" :class="cur.dir === 'in' ? 'bg-gradient-to-r from-emerald-600 to-teal-600' : 'bg-gradient-to-r from-indigo-600 to-violet-600'">
            <h3 class="text-white font-bold" x-text="cur.dir === 'in' ? 'Cash received from the seller' : 'Payment made to the seller'"></h3>
            <p class="text-white/80 text-[12px]" x-text="cur.name"></p>
        </div>
        <form method="POST" class="p-5 space-y-3">
            <input type="hidden" name="seller_id" :value="cur.id">
            <input type="hidden" name="direction" :value="cur.dir">
            <input type="hidden" name="back" value="<?php echo htmlspecialchars($backq); ?>">
            <div>
                <label class="lbl">Amount</label>
                <input type="number" step="0.01" min="0.01" name="amount" class="fld" :value="cur.dir === 'in' ? cur.holding : ''" required>
                <p class="text-[11px] text-slate-400 mt-1" x-show="cur.dir === 'in'" x-text="'They are holding ₹' + Number(cur.holding).toFixed(2) + '.'"></p>
            </div>
            <div>
                <label class="lbl">How</label>
                <select name="mode" class="fld">
                    <option value="cash">Cash</option>
                    <option value="online">Bank / UPI transfer</option>
                    <option value="adjust">Adjusted against something else</option>
                </select>
            </div>
            <div>
                <label class="lbl">Reference</label>
                <input name="reference" class="fld" maxlength="120" placeholder="Receipt or transaction number">
            </div>
            <div>
                <label class="lbl">Note</label>
                <input name="note" class="fld" maxlength="200">
            </div>
            <div class="flex justify-end gap-2 pt-1">
                <button type="button" @click="box = null" class="px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-100 rounded-lg">Cancel</button>
                <button name="settle" value="1" class="px-5 py-2 text-sm font-bold text-white rounded-lg shadow"
                        :class="cur.dir === 'in' ? 'bg-emerald-600 hover:bg-emerald-700' : 'bg-indigo-600 hover:bg-indigo-700'">Record it</button>
            </div>
        </form>
    </div>
</div>

<!-- assign a seller -->
<div x-show="box === 'assign'" x-transition.opacity style="display:none" class="fixed inset-0 z-[110] flex items-center justify-center p-4">
    <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="box = null"></div>
    <div class="relative w-full max-w-md bg-white rounded-2xl shadow-2xl overflow-hidden">
        <div class="bg-gradient-to-r from-slate-800 to-slate-900 px-5 py-4">
            <h3 class="text-white font-bold">Who is going out?</h3>
            <p class="text-slate-300 text-[12px]" x-text="'Order ' + cur.code"></p>
        </div>
        <form method="POST" class="p-5 space-y-3">
            <input type="hidden" name="order_id" :value="cur.id">
            <input type="hidden" name="back" value="<?php echo htmlspecialchars($backq); ?>">
            <div>
                <label class="lbl">Seller</label>
                <select name="new_seller_id" class="fld" required>
                    <option value="">— pick one —</option>
                    <?php foreach ($sellers as $s): ?>
                        <option value="<?php echo (int)$s['id']; ?>"><?php echo htmlspecialchars($s['name']); ?> · <?php echo htmlspecialchars($s['mobile']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="flex justify-end gap-2">
                <button type="button" @click="box = null" class="px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-100 rounded-lg">Cancel</button>
                <button name="assign_seller" value="1" class="px-5 py-2 text-sm font-bold text-white bg-slate-900 hover:bg-slate-700 rounded-lg shadow">Assign</button>
            </div>
        </form>
    </div>
</div>

<!-- cancel an order -->
<div x-show="box === 'cancel'" x-transition.opacity style="display:none" class="fixed inset-0 z-[110] flex items-center justify-center p-4">
    <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="box = null"></div>
    <div class="relative w-full max-w-md bg-white rounded-2xl shadow-2xl overflow-hidden">
        <div class="bg-gradient-to-r from-rose-500 to-red-600 px-5 py-4">
            <h3 class="text-white font-bold">Cancel this order</h3>
            <p class="text-rose-50 text-[12px]" x-text="cur.code"></p>
        </div>
        <form method="POST" class="p-5 space-y-3">
            <input type="hidden" name="order_id" :value="cur.id">
            <input type="hidden" name="back" value="<?php echo htmlspecialchars($backq); ?>">
            <div>
                <label class="lbl">Reason</label>
                <input name="reason" class="fld" maxlength="200" required>
            </div>
            <label class="flex items-start gap-2 bg-amber-50 border border-amber-200 rounded-lg p-3 cursor-pointer">
                <input type="checkbox" name="refund" value="1" checked class="mt-0.5 accent-amber-600">
                <span class="text-[12px] font-bold text-slate-700">Put what was paid online back into their wallet
                    <span class="block font-normal text-[11px] text-slate-500 mt-0.5">Cash a seller already took is not touched — settle that separately.</span>
                </span>
            </label>
            <div class="flex justify-end gap-2">
                <button type="button" @click="box = null" class="px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-100 rounded-lg">Keep it</button>
                <button name="cancel_order" value="1" class="px-5 py-2 text-sm font-bold text-white bg-rose-600 hover:bg-rose-700 rounded-lg shadow">Cancel the order</button>
            </div>
        </form>
    </div>
</div>

<script>
function omBoard() {
    return {
        sidebarOpen: window.innerWidth >= 768,
        box: null,
        cur: { id: 0, code: '', due: 0, seller: 0, amount: 0, name: '', holding: 0, dir: 'in' },

        takeMoney(id, code, due, seller) { this.cur = { id: id, code: code, due: due, seller: seller }; this.box = 'money'; },
        reject(id, amount)               { this.cur = { id: id, amount: amount }; this.box = 'reject'; },
        settle(id, name, holding, dir)   { this.cur = { id: id, name: name, holding: holding, dir: dir }; this.box = 'settle'; },
        assign(id, code)                 { this.cur = { id: id, code: code }; this.box = 'assign'; },
        cancel(id, code)                 { this.cur = { id: id, code: code }; this.box = 'cancel'; }
    };
}
</script>

</body>
</html>
