<?php
/* ============================================================================
   WBMCZ — VISIT & ADVANCE: TOP-UP AND HEALTH CHECK
   Run once:   https://wbmcz.online/offmigration.php     then DELETE this file.
   ----------------------------------------------------------------------------
   ordmigration.php already builds the schema for visit-based selling. This file
   does NOT replace it. It exists for three reasons:

     1  IT DOES NOT ASSUME ordmigration.php WAS EVER RUN.
        Every column and table is checked and created if missing, so if that
        file was uploaded but never opened, this one closes the gap. If it was
        run, every step below simply reports "already there" and changes nothing.

     2  THE PAYOUT BACKFILL — the one thing nothing else does.
        The admin Financial Overview reads seller_payout and company_profit off
        the order row. Orders placed before those columns existed hold zero, so
        the whole panel would read zero however much money has actually been
        made. product_share_ledger knows the real figures for those orders, so
        they are copied across.

     3  A HEALTH CHECK.
        It prints what it FOUND, not only what it changed, so you can see the
        system is complete before letting a customer near it.

   Nothing here deletes or overwrites live data. Safe to run more than once.
   ============================================================================ */

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';

@set_time_limit(300);
$conn = $db->getConnection();
$log  = [];

function off_table($conn, $t) {
    try { $r = $conn->query("SHOW TABLES LIKE '$t'"); return $r && $r->num_rows > 0; }
    catch (\Throwable $e) { return false; }
}
function off_col($conn, $t, $c) {
    try { $r = $conn->query("SHOW COLUMNS FROM `$t` LIKE '$c'"); return $r && $r->num_rows > 0; }
    catch (\Throwable $e) { return false; }
}
function off_add(&$log, $conn, $t, $c, $def) {
    if (!off_table($conn, $t))  { $log[] = ['skip', "$t.$c", 'that table does not exist on this database']; return; }
    if (off_col($conn, $t, $c)) { $log[] = ['ok',   "$t.$c", 'already there'];  return; }
    try { $conn->query("ALTER TABLE `$t` ADD COLUMN `$c` $def"); $log[] = ['add', "$t.$c", $def]; }
    catch (\Throwable $e) { $log[] = ['fail', "$t.$c", $e->getMessage()]; }
}
function off_create(&$log, $conn, $t, $sql) {
    if (off_table($conn, $t)) { $log[] = ['ok', $t, 'table already exists']; return; }
    try { $conn->query($sql); $log[] = ['add', $t, 'table created']; }
    catch (\Throwable $e) { $log[] = ['fail', $t, $e->getMessage()]; }
}
function off_index(&$log, $conn, $t, $name, $sql) {
    if (!off_table($conn, $t)) return;
    try {
        $r = $conn->query("SHOW INDEX FROM `$t` WHERE Key_name = '$name'");
        if ($r && $r->num_rows > 0) { $log[] = ['ok', "$t · $name", 'index already there']; return; }
        $conn->query("ALTER TABLE `$t` ADD $sql");
        $log[] = ['add', "$t · $name", 'index created'];
    } catch (\Throwable $e) { $log[] = ['fail', "$t · $name", $e->getMessage()]; }
}
function off_note(&$log, $what, $msg) { $log[] = ['note', $what, $msg]; }

/* ===========================================================================
   1 · THE PRODUCT — how it is delivered, and what is asked for up front
   ======================================================================== */
foreach (['seller_services', 'agency_services'] as $t) {
    off_add($log, $conn, $t, 'fulfilment',      "VARCHAR(20) NOT NULL DEFAULT 'online'");
    off_add($log, $conn, $t, 'advance_mode',    "VARCHAR(20) NOT NULL DEFAULT 'company'");
    off_add($log, $conn, $t, 'advance_amount',  "DECIMAL(10,2) NOT NULL DEFAULT 0.00");
    off_add($log, $conn, $t, 'advance_percent', "DECIMAL(5,2) NOT NULL DEFAULT 0.00");
    off_add($log, $conn, $t, 'allow_cart',      "TINYINT(1) NOT NULL DEFAULT 1");
    off_add($log, $conn, $t, 'allow_code',      "TINYINT(1) NOT NULL DEFAULT 1");
    off_add($log, $conn, $t, 'visit_note',      "VARCHAR(255) NULL");
}
off_index($log, $conn, 'seller_services', 'idx_ss_fulfil', 'INDEX idx_ss_fulfil (fulfilment)');

/* the category-wide default a product falls back to */
off_add($log, $conn, 'service_categories', 'fulfilment',      "VARCHAR(20) NOT NULL DEFAULT 'online'");
off_add($log, $conn, 'service_categories', 'advance_mode',    "VARCHAR(20) NOT NULL DEFAULT 'company'");
off_add($log, $conn, 'service_categories', 'advance_percent', "DECIMAL(5,2) NOT NULL DEFAULT 0.00");
off_add($log, $conn, 'service_categories', 'advance_amount',  "DECIMAL(10,2) NOT NULL DEFAULT 0.00");

/* ===========================================================================
   2 · THE ORDER — what was paid, what is owed, and where it has got to
   ======================================================================== */
foreach ([
    'order_code'          => "VARCHAR(40) NULL",
    'fulfilment'          => "VARCHAR(20) NOT NULL DEFAULT 'online'",
    'customer_type'       => "VARCHAR(20) NOT NULL DEFAULT 'regular'",
    'payment_mode'        => "VARCHAR(20) NOT NULL DEFAULT 'full'",
    'mrp'                 => "DECIMAL(10,2) NOT NULL DEFAULT 0.00",
    'base_amount'         => "DECIMAL(10,2) NOT NULL DEFAULT 0.00",
    'discount_amount'     => "DECIMAL(10,2) NOT NULL DEFAULT 0.00",
    'paid_amount'         => "DECIMAL(10,2) NOT NULL DEFAULT 0.00",
    'wallet_used'         => "DECIMAL(10,2) NOT NULL DEFAULT 0.00",
    'gateway_used'        => "DECIMAL(10,2) NOT NULL DEFAULT 0.00",
    'due_amount'          => "DECIMAL(10,2) NOT NULL DEFAULT 0.00",
    'collected_amount'    => "DECIMAL(10,2) NOT NULL DEFAULT 0.00",
    'collected_mode'      => "VARCHAR(20) NULL",
    'collected_at'        => "DATETIME NULL",
    'collected_by'        => "INT NULL",
    'seller_payout'       => "DECIMAL(10,2) NOT NULL DEFAULT 0.00",
    'company_profit'      => "DECIMAL(10,2) NOT NULL DEFAULT 0.00",
    'payment_code'        => "VARCHAR(30) NULL",
    'payment_code_status' => "VARCHAR(20) NOT NULL DEFAULT 'none'",
    'visit_status'        => "VARCHAR(20) NOT NULL DEFAULT 'none'",
    'visit_at'            => "DATETIME NULL",
    'stage'               => "VARCHAR(30) NOT NULL DEFAULT 'placed'",
    'customer_name'       => "VARCHAR(150) NULL",
    'customer_mobile'     => "VARCHAR(25) NULL",
    'address'             => "VARCHAR(500) NULL",
    'note'                => "VARCHAR(500) NULL",
    'item_count'          => "INT NOT NULL DEFAULT 1",
    'updated_at'          => "TIMESTAMP NULL DEFAULT NULL",
] as $c => $d) { off_add($log, $conn, 'orders', $c, $d); }

off_index($log, $conn, 'orders', 'idx_orders_stage',  'INDEX idx_orders_stage (stage)');
off_index($log, $conn, 'orders', 'idx_orders_due',    'INDEX idx_orders_due (due_amount)');
off_index($log, $conn, 'orders', 'idx_orders_seller', 'INDEX idx_orders_seller (seller_id, stage)');
off_index($log, $conn, 'orders', 'uniq_order_code',   'UNIQUE INDEX uniq_order_code (order_code)');

/* ===========================================================================
   3 · THE FIVE TABLES the flow needs
   ======================================================================== */
off_create($log, $conn, 'carts', "CREATE TABLE carts (
    id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, service_id INT NOT NULL,
    service_type VARCHAR(20) NOT NULL DEFAULT 'seller', qty INT NOT NULL DEFAULT 1,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY uniq_cart (user_id, service_id, service_type), KEY idx_cart_user (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

off_create($log, $conn, 'order_items', "CREATE TABLE order_items (
    id INT AUTO_INCREMENT PRIMARY KEY, order_id INT NOT NULL, service_id INT NOT NULL,
    service_type VARCHAR(20) NOT NULL DEFAULT 'seller', title VARCHAR(255) NOT NULL,
    category_id INT NULL, seller_id INT NULL, seller_name VARCHAR(150) NULL, seller_mobile VARCHAR(25) NULL,
    qty INT NOT NULL DEFAULT 1, mrp DECIMAL(10,2) NOT NULL DEFAULT 0.00,
    base_price DECIMAL(10,2) NOT NULL DEFAULT 0.00, discount DECIMAL(10,2) NOT NULL DEFAULT 0.00,
    amount DECIMAL(10,2) NOT NULL DEFAULT 0.00, advance DECIMAL(10,2) NOT NULL DEFAULT 0.00,
    due DECIMAL(10,2) NOT NULL DEFAULT 0.00, seller_payout DECIMAL(10,2) NOT NULL DEFAULT 0.00,
    company_profit DECIMAL(10,2) NOT NULL DEFAULT 0.00, fulfilment VARCHAR(20) NOT NULL DEFAULT 'online',
    status VARCHAR(30) NOT NULL DEFAULT 'pending', created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    KEY idx_oi_order (order_id), KEY idx_oi_seller (seller_id, status), KEY idx_oi_service (service_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

off_create($log, $conn, 'order_timeline', "CREATE TABLE order_timeline (
    id BIGINT AUTO_INCREMENT PRIMARY KEY, order_id INT NOT NULL, order_code VARCHAR(40) NULL,
    stage VARCHAR(30) NOT NULL, title VARCHAR(160) NOT NULL, note VARCHAR(500) NULL,
    amount DECIMAL(10,2) NULL, actor_id INT NULL, actor_name VARCHAR(150) NULL,
    actor_role VARCHAR(20) NULL, ip_address VARCHAR(45) NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, KEY idx_ot_order (order_id, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

off_create($log, $conn, 'seller_collections', "CREATE TABLE seller_collections (
    id INT AUTO_INCREMENT PRIMARY KEY, order_id INT NOT NULL, order_code VARCHAR(40) NULL,
    item_id INT NULL, seller_id INT NOT NULL, customer_id INT NULL, customer_name VARCHAR(150) NULL,
    amount DECIMAL(10,2) NOT NULL DEFAULT 0.00, mode VARCHAR(20) NOT NULL DEFAULT 'cash',
    reference VARCHAR(120) NULL, note VARCHAR(500) NULL, status VARCHAR(20) NOT NULL DEFAULT 'pending',
    recorded_by INT NULL, recorded_by_name VARCHAR(150) NULL, approved_by INT NULL,
    approved_by_name VARCHAR(150) NULL, approved_at DATETIME NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    KEY idx_sc_order (order_id), KEY idx_sc_seller (seller_id, status), KEY idx_sc_status (status, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

off_create($log, $conn, 'seller_settlements', "CREATE TABLE seller_settlements (
    id INT AUTO_INCREMENT PRIMARY KEY, seller_id INT NOT NULL, direction VARCHAR(10) NOT NULL DEFAULT 'in',
    amount DECIMAL(10,2) NOT NULL DEFAULT 0.00, mode VARCHAR(20) NOT NULL DEFAULT 'cash',
    reference VARCHAR(120) NULL, note VARCHAR(500) NULL, order_id INT NULL, created_by INT NULL,
    created_by_name VARCHAR(150) NULL, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    KEY idx_st_seller (seller_id, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

/* ===========================================================================
   4 · OLD ORDERS — described honestly as what they were
   ---------------------------------------------------------------------------
   Everything bought before this existed was paid in full, online, in one go.
   Say so on the row rather than leaving zeroes that read as "unpaid".
   ======================================================================== */
if (off_table($conn, 'orders') && off_col($conn, 'orders', 'paid_amount')) {
    try {
        $conn->query("UPDATE orders
                         SET paid_amount = amount, due_amount = 0, item_count = 1
                       WHERE paid_amount = 0 AND due_amount = 0 AND amount > 0");
        $n = $conn->affected_rows;
        off_note($log, 'old orders', $n > 0
            ? "$n order(s) marked as fully paid — that is what they were"
            : 'nothing needed changing');
    } catch (\Throwable $e) { $log[] = ['fail', 'old orders', $e->getMessage()]; }

    /* the stage column has to agree with the status column */
    try {
        $conn->query("UPDATE orders SET stage = CASE
                          WHEN status = 'Completed' THEN 'completed'
                          WHEN status = 'Cancelled' THEN 'cancelled'
                          WHEN status = 'Failed'    THEN 'cancelled'
                          ELSE 'paid' END
                       WHERE stage = 'placed' AND COALESCE(order_code,'') = ''");
        off_note($log, 'order stages', $conn->affected_rows . " old order(s) given a stage matching their status");
    } catch (\Throwable $e) { $log[] = ['fail', 'order stages', $e->getMessage()]; }

    /* an order code for every old order, so nothing on screen shows a blank */
    try {
        $rows = $db->select("SELECT id, created_at FROM orders WHERE COALESCE(order_code,'') = '' ORDER BY id ASC");
        $n = 0;
        foreach ($rows as $r) {
            $code = 'WBMCZ-' . date('ymd', strtotime($r['created_at'])) . '-' . str_pad((int)$r['id'], 6, '0', STR_PAD_LEFT);
            try { $db->insert("UPDATE orders SET order_code = ? WHERE id = ?", [$code, (int)$r['id']]); $n++; }
            catch (\Throwable $e) {}
        }
        off_note($log, 'order codes', $n > 0 ? "$n old order(s) given an order code" : 'every order already has a code');
    } catch (\Throwable $e) { $log[] = ['fail', 'order codes', $e->getMessage()]; }
}

/* ===========================================================================
   5 · THE PAYOUT BACKFILL
   ---------------------------------------------------------------------------
   The admin Financial Overview reads seller_payout and company_profit off the
   order row. Orders placed before those columns existed hold zero, which would
   make the whole panel read zero. product_share_ledger already knows the real
   numbers for those orders, so copy them across.
   ======================================================================== */
if (off_table($conn, 'orders') && off_table($conn, 'product_share_ledger')) {
    try {
        $conn->query("UPDATE orders o
                      JOIN (SELECT order_id,
                                   SUM(CASE WHEN share_type = 'seller'  THEN amount ELSE 0 END) sp,
                                   SUM(CASE WHEN share_type = 'company' THEN amount ELSE 0 END) cp
                              FROM product_share_ledger
                             GROUP BY order_id) l ON l.order_id = o.id
                         SET o.seller_payout  = l.sp,
                             o.company_profit = l.cp
                       WHERE o.seller_payout = 0 AND o.company_profit = 0");
        off_note($log, 'payout backfill', $conn->affected_rows . ' old order(s) given their real payout and profit figures');
    } catch (\Throwable $e) { $log[] = ['fail', 'payout backfill', $e->getMessage()]; }
} else {
    off_note($log, 'payout backfill', 'skipped — no share ledger on this database');
}

/* ===========================================================================
   6 · THE SETTING
   ======================================================================== */
if (off_table($conn, 'settings')) {
    try {
        $has = $db->select("SELECT id FROM settings WHERE setting_key = 'show_payout_public' LIMIT 1");
        if (empty($has)) {
            $db->insert("INSERT INTO settings (setting_key, setting_value) VALUES ('show_payout_public', '1')");
            off_note($log, 'show_payout_public', 'added, set to 1 — customers see the seller payout and company profit');
        } else {
            off_note($log, 'show_payout_public', 'already set — left exactly as it is');
        }
    } catch (\Throwable $e) {
        /* some installs name the columns differently; not worth failing over */
        off_note($log, 'show_payout_public', 'could not be written automatically — add it in Website Settings if you want to change the default');
    }
}

/* ===========================================================================
   7 · HEALTH CHECK — is the system actually complete?
   ======================================================================== */
$health = [];
foreach (['carts', 'order_items', 'order_timeline', 'seller_collections', 'seller_settlements'] as $t) {
    $health[] = [$t, off_table($conn, $t)];
}
foreach (['orders.stage', 'orders.due_amount', 'orders.order_code',
          'seller_services.fulfilment', 'service_categories.fulfilment'] as $k) {
    [$t, $c] = explode('.', $k);
    $health[] = [$k, off_col($conn, $t, $c)];
}
$files = [];
foreach (['includes/purchase.php', 'order.php', 'product.php', 'cart.php', 'checkout.php',
          'admin/order_manage.php', 'admin/services.php', 'admin/product_management.php',
          'seller/collections.php'] as $f) {
    $files[] = [$f, file_exists(__DIR__ . '/' . $f)];
}

$counts = ['visit_products' => 0, 'visit_orders' => 0, 'due_total' => 0.0, 'pending_claims' => 0];
try { $r = $db->select("SELECT COUNT(*) c FROM seller_services WHERE fulfilment = 'visit'"); $counts['visit_products'] = (int)($r[0]['c'] ?? 0); } catch (\Throwable $e) {}
try { $r = $db->select("SELECT COUNT(*) c, COALESCE(SUM(due_amount),0) s FROM orders WHERE due_amount > 0");
      $counts['visit_orders'] = (int)($r[0]['c'] ?? 0); $counts['due_total'] = (float)($r[0]['s'] ?? 0); } catch (\Throwable $e) {}
try { $r = $db->select("SELECT COUNT(*) c FROM seller_collections WHERE status = 'pending'"); $counts['pending_claims'] = (int)($r[0]['c'] ?? 0); } catch (\Throwable $e) {}

$n_add = 0; $n_fail = 0;
foreach ($log as $l) { if ($l[0] === 'add') $n_add++; if ($l[0] === 'fail') $n_fail++; }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WBMCZ — Offline / Advance Payment Migration</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
  body { font-family:'Inter',system-ui,sans-serif; background:#f1f5f9; margin:0; padding:32px 16px; color:#0f172a; }
  .wrap { max-width:920px; margin:0 auto; }
  .card { background:#fff; border:1px solid #e2e8f0; border-radius:18px; padding:26px; margin-bottom:20px;
          box-shadow:0 10px 30px -24px rgba(15,23,42,.6); }
  h1 { margin:0 0 6px; font-size:1.6rem; font-weight:800; }
  h2 { margin:0 0 14px; font-size:1.05rem; font-weight:800; }
  p.sub { margin:0 0 22px; color:#64748b; font-size:.92rem; }
  table { width:100%; border-collapse:collapse; font-size:.86rem; }
  th { text-align:left; padding:9px 10px; background:#f8fafc; color:#64748b; font-size:.7rem;
       text-transform:uppercase; letter-spacing:.08em; border-bottom:1px solid #e2e8f0; }
  td { padding:9px 10px; border-bottom:1px solid #f1f5f9; vertical-align:top; }
  .tag { display:inline-block; padding:2px 9px; border-radius:999px; font-size:.66rem; font-weight:800; }
  .t-add  { background:#dcfce7; color:#15803d; }
  .t-ok   { background:#e2e8f0; color:#475569; }
  .t-skip { background:#fef3c7; color:#b45309; }
  .t-fail { background:#fee2e2; color:#b91c1c; }
  .t-note { background:#dbeafe; color:#1d4ed8; }
  .yes { color:#15803d; font-weight:800; }
  .no  { color:#b91c1c; font-weight:800; }
  .grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(190px,1fr)); gap:12px; }
  .stat { background:#0f172a; color:#fff; border-radius:14px; padding:14px 16px; }
  .stat b { display:block; font-size:1.5rem; margin-top:3px; }
  .warn { background:#fffbeb; border:1px solid #fde68a; color:#92400e; border-radius:14px; padding:14px 16px;
          font-size:.88rem; line-height:1.6; }
  .good { background:#f0fdf4; border:1px solid #bbf7d0; color:#166534; border-radius:14px; padding:14px 16px;
          font-size:.88rem; line-height:1.6; }
  code { background:#f1f5f9; padding:1px 6px; border-radius:5px; font-size:.85em; }
</style>
</head>
<body>
<div class="wrap">

  <div class="card">
    <h1>Offline / advance-payment migration</h1>
    <p class="sub">
      <?php echo $n_add; ?> change<?php echo $n_add === 1 ? '' : 's'; ?> applied ·
      <?php echo $n_fail; ?> failure<?php echo $n_fail === 1 ? '' : 's'; ?> ·
      run at <?php echo date('d M Y, h:i A'); ?>
    </p>

    <?php if ($n_fail === 0): ?>
      <div class="good">
        <b>Everything went through.</b> The visit-and-advance system has what it needs.
        Delete this file from the server now — it should not stay reachable on a live site.
      </div>
    <?php else: ?>
      <div class="warn">
        <b><?php echo $n_fail; ?> step<?php echo $n_fail === 1 ? '' : 's'; ?> failed.</b>
        Look at the red rows below before using the new screens. A failure here usually means the
        database user cannot ALTER tables, or a table has a different name on this install.
      </div>
    <?php endif; ?>
  </div>

  <div class="card">
    <h2>What is on the database now</h2>
    <div class="grid" style="margin-bottom:18px">
      <div class="stat">Products sold by visit <b><?php echo number_format($counts['visit_products']); ?></b></div>
      <div class="stat">Orders with money owed <b><?php echo number_format($counts['visit_orders']); ?></b></div>
      <div class="stat">Still to collect <b>₹<?php echo number_format($counts['due_total'], 0); ?></b></div>
      <div class="stat">Waiting on the office <b><?php echo number_format($counts['pending_claims']); ?></b></div>
    </div>

    <table>
      <thead><tr><th>Table or column</th><th style="width:110px">Present</th></tr></thead>
      <tbody>
        <?php foreach ($health as $h): ?>
          <tr><td><code><?php echo htmlspecialchars($h[0]); ?></code></td>
              <td class="<?php echo $h[1] ? 'yes' : 'no'; ?>"><?php echo $h[1] ? 'yes' : 'MISSING'; ?></td></tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <div class="card">
    <h2>Files the system needs</h2>
    <p class="sub" style="margin-bottom:14px">
      A missing file here means an upload was not completed. The pages that depend on it will 404.
    </p>
    <table>
      <thead><tr><th>File</th><th style="width:110px">Uploaded</th></tr></thead>
      <tbody>
        <?php foreach ($files as $f): ?>
          <tr><td><code><?php echo htmlspecialchars($f[0]); ?></code></td>
              <td class="<?php echo $f[1] ? 'yes' : 'no'; ?>"><?php echo $f[1] ? 'yes' : 'MISSING'; ?></td></tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <div class="card">
    <h2>Every step, in order</h2>
    <table>
      <thead><tr><th style="width:80px">Result</th><th>What</th><th>Detail</th></tr></thead>
      <tbody>
        <?php foreach ($log as $l): ?>
          <tr>
            <td><span class="tag t-<?php echo $l[0]; ?>"><?php echo strtoupper($l[0]); ?></span></td>
            <td><code><?php echo htmlspecialchars($l[1]); ?></code></td>
            <td style="color:#64748b"><?php echo htmlspecialchars($l[2]); ?></td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <div class="card">
    <h2>What to do next</h2>
    <ol style="margin:0; padding-left:20px; color:#334155; font-size:.9rem; line-height:1.85">
      <li><b>Delete this file</b> from the server.</li>
      <li>Open <code>Admin &rarr; Service Management &rarr; Main Categories</code> and set which
          categories sell by seller visit, and how much is taken as advance.</li>
      <li><code>Admin &rarr; Product Management</code> can override that for a single product
          that is different. A product left on "follow the category" does exactly that.</li>
      <li><b>Company share</b> is the advance setting to prefer: the customer pays what the
          company earns, the seller keeps what the seller earns, and no money has to move
          between them afterwards.</li>
      <li>Buy one thing yourself, end to end &mdash; advance, visit, cash, verify &mdash;
          before telling any seller about it.</li>
    </ol>
  </div>

</div>
</body>
</html>
