<?php
/* ============================================================================
   WBMCZ — LIVE CHECK  (temporary, delete after use)
   ----------------------------------------------------------------------------
   Read-only. It changes nothing. It answers three questions at once:
     1. Which of the new files actually reached this server, and are they the
        same size as the ones that were sent?
     2. Has ordmigration.php been run here — do the new columns and tables exist?
     3. For the account that is logged in right now, why does a product card
        look the way it does: purchased, KYC-blocked, area-blocked, or buyable?
   ============================================================================ */
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/includes/functions.php';

$conn = $db->getConnection();

/* ---- 1. files ---- */
$want = [
    'includes/purchase.php'         => 69702,
    'includes/shares.php'           => 34354,
    'includes/theme.php'            => 38259,
    'product.php'                   => 28940,
    'cart.php'                      => 14732,
    'checkout.php'                  => 26993,
    'order.php'                     => 28272,
    'orders.php'                    => 15884,
    'category.php'                  => 77046,
    'admin/order_manage.php'        => 43478,
    'admin/product_management.php'  => 122166,
    'admin/services.php'            => 38758,
    'admin/includes/sidebar.php'    => 40427,
    'seller/collections.php'        => 25855,
    'seller/services.php'           => 51410,
];

/* ---- 2. schema ---- */
function lc_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 lc_table($conn, $t) {
    try { $r = $conn->query("SHOW TABLES LIKE '$t'"); return $r && $r->num_rows > 0; }
    catch (\Throwable $e) { return false; }
}
$cols = [
    'seller_services.fulfilment'   => lc_col($conn, 'seller_services', 'fulfilment'),
    'seller_services.advance_mode' => lc_col($conn, 'seller_services', 'advance_mode'),
    'seller_services.allow_cart'   => lc_col($conn, 'seller_services', 'allow_cart'),
    'service_categories.fulfilment'=> lc_col($conn, 'service_categories', 'fulfilment'),
    'orders.order_code'            => lc_col($conn, 'orders', 'order_code'),
    'orders.due_amount'            => lc_col($conn, 'orders', 'due_amount'),
    'orders.stage'                 => lc_col($conn, 'orders', 'stage'),
];
$tabs = [];
foreach (['carts', 'order_items', 'order_timeline', 'seller_collections', 'seller_settlements'] as $t) {
    $tabs[$t] = lc_table($conn, $t);
}
/* is fulfilment nullable — the "follow the category" behaviour depends on it */
$nullable = '—';
try {
    $r = $conn->query("SHOW COLUMNS FROM seller_services LIKE 'fulfilment'");
    if ($r && ($row = $r->fetch_assoc())) { $nullable = $row['Null'] . ' / default ' . var_export($row['Default'], true); }
} catch (\Throwable $e) {}

/* ---- 3. this account ---- */
$uid  = (int)($_SESSION['user_id'] ?? 0);
$me   = null; $rows = []; $kyc = null;
if ($uid > 0) {
    $u = $db->select("SELECT id, name, mobile, user_type, is_subscribed, wallet_balance FROM users WHERE id = ?", [$uid]);
    $me = $u[0] ?? null;
    /* the real table the gate reads */
    try { $k = $db->select("SELECT * FROM kyc_details WHERE user_id = ? LIMIT 1", [$uid]); $kyc = $k[0] ?? null; } catch (\Throwable $e) {}

    $cat = isset($_GET['cat']) ? (int)$_GET['cat'] : 5;
    $svcs = $db->select("SELECT * FROM seller_services WHERE category_id = ? AND status = 1 ORDER BY id LIMIT 12", [$cat]);

    $ord = $db->select("SELECT service_name, status FROM orders WHERE user_id = ?", [$uid]);
    $bought = [];
    foreach ($ord as $o) { $bought[$o['service_name']] = $o['status']; }

    $has_engine = file_exists(__DIR__ . '/includes/purchase.php');
    if ($has_engine) {
        require_once __DIR__ . '/includes/shares.php';
        require_once __DIR__ . '/includes/wallet.php';
        require_once __DIR__ . '/includes/purchase.php';
    }

    foreach ($svcs as $s) {
        $row = ['title' => $s['title'], 'price' => $s['discount_price'] > 0 ? $s['discount_price'] : $s['price']];
        $row['order_status'] = $bought[$s['title']] ?? '—';
        $row['card'] = ($s['price'] <= 0 && $s['discount_price'] <= 0) ? 'free-card'
                     : (($row['order_status'] === 'Completed') ? 'PURCHASED'
                     : ((in_array($row['order_status'], ['Pending', 'Processing'], true)) ? 'pending' : 'buyable'));
        if ($has_engine && function_exists('product_purchase_gate')) {
            $g = product_purchase_gate($db, $s, $uid);
            $row['gate'] = $g['ok'] ? 'OK' : (empty($g['area']['ok']) ? 'AREA blocked' : 'KYC blocked');
            $k = $g['kyc'] ?? [];
            $row['why'] = ($k['reason'] ?? '—') . ' · kyc status = ' . ($k['status'] ?? '—');
            $need = $k['required'] ?? []; $miss = $k['missing'] ?? [];
            $row['need'] = count($need) . ' required, ' . count($miss) . ' still blank'
                         . (count($miss) ? ': ' . implode(', ', array_slice($miss, 0, 6)) . (count($miss) > 6 ? ' …' : '') : '');
            $q = buy_quote($db, $s, $uid);
            $row['sells'] = $q['fulfilment'] . ' · own=' . var_export($s['fulfilment'] ?? null, true);
            $row['pay']   = number_format($q['payable'], 2);
        }
        $rows[] = $row;
    }
}

function yn($b) { return $b ? '<b style="color:#059669">yes</b>' : '<b style="color:#dc2626">NO</b>'; }
?><!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Live check</title>
<style>
 body{font-family:system-ui,Segoe UI,Arial,sans-serif;background:#f8fafc;margin:0;padding:24px;color:#0f172a}
 .w{max-width:1000px;margin:0 auto}
 h1{font-size:20px;margin:0 0 4px} h2{font-size:14px;margin:26px 0 8px;text-transform:uppercase;letter-spacing:.06em;color:#64748b}
 table{width:100%;border-collapse:collapse;background:#fff;border:1px solid #e2e8f0;border-radius:12px;overflow:hidden;font-size:13px}
 th{background:#f1f5f9;text-align:left;padding:9px 11px;font-size:11px;text-transform:uppercase;letter-spacing:.05em;color:#64748b}
 td{padding:9px 11px;border-top:1px solid #f1f5f9}
 .bad{color:#dc2626;font-weight:700} .good{color:#059669;font-weight:700} .warn{color:#b45309;font-weight:700}
 .note{background:#fff7ed;border:1px solid #fed7aa;color:#9a3412;padding:12px 14px;border-radius:12px;margin-top:18px;font-size:13px}
</style></head><body><div class="w">
<h1>WBMCZ live check</h1>
<p style="color:#64748b;font-size:13px;margin:0">PHP <?php echo PHP_VERSION; ?> · <?php echo date('d M Y, g:i A'); ?> · database <code><?php echo DB_NAME; ?></code></p>

<h2>1 · Files on this server</h2>
<table><tr><th>File</th><th>Present</th><th>Size here</th><th>Size sent</th><th>Same?</th><th>Uploaded</th></tr>
<?php foreach ($want as $f => $size):
    $p = __DIR__ . '/' . $f; $ex = file_exists($p); $sz = $ex ? filesize($p) : 0; ?>
<tr>
  <td><code><?php echo htmlspecialchars($f); ?></code></td>
  <td><?php echo yn($ex); ?></td>
  <td><?php echo $ex ? number_format($sz) : '—'; ?></td>
  <td><?php echo number_format($size); ?></td>
  <td><?php echo $ex ? ($sz === $size ? '<span class="good">same</span>' : '<span class="bad">DIFFERENT &mdash; old file</span>') : '<span class="bad">missing</span>'; ?></td>
  <td><?php echo $ex ? date('d M, g:i A', filemtime($p)) : '—'; ?></td>
</tr>
<?php endforeach; ?>
</table>

<h2>2 · Database — has ordmigration.php been run here?</h2>
<table><tr><th>Column</th><th>Exists</th></tr>
<?php foreach ($cols as $k => $v): ?>
<tr><td><code><?php echo $k; ?></code></td><td><?php echo yn($v); ?></td></tr>
<?php endforeach; ?>
<?php foreach ($tabs as $k => $v): ?>
<tr><td>table <code><?php echo $k; ?></code></td><td><?php echo yn($v); ?></td></tr>
<?php endforeach; ?>
<tr><td><code>seller_services.fulfilment</code> nullable?</td><td><?php echo htmlspecialchars($nullable); ?>
    <?php if (strpos($nullable, 'YES') === false): ?><span class="bad"> &larr; run ordmigration.php again</span><?php endif; ?></td></tr>
</table>

<h2>3 · The account logged in right now</h2>
<?php if (!$me): ?>
  <p class="bad">Nobody is logged in. Log in on this site in the same browser, then open this page again.</p>
<?php else: ?>
  <table>
    <tr><th>Who</th><td><?php echo htmlspecialchars($me['name']); ?> (id <?php echo (int)$me['id']; ?>, <?php echo htmlspecialchars($me['user_type']); ?>)</td></tr>
    <tr><th>Subscriber</th><td><?php echo ((int)$me['is_subscribed'] === 1 ? 'yes' : 'no'); ?></td></tr>
    <tr><th>Wallet</th><td>&#8377;<?php echo number_format((float)$me['wallet_balance'], 2); ?></td></tr>
    <tr><th>KYC row (<code>kyc_details</code>)</th><td><?php
        if (!$kyc) { echo '<span class="bad">no row &mdash; this account has never submitted KYC</span>'; }
        else {
            $st = (string)($kyc['status'] ?? '');
            echo 'status = <b class="' . ($st === 'approved' ? 'good' : 'bad') . '">' . htmlspecialchars($st ?: 'blank') . '</b>';
            if (!empty($kyc['admin_remark'])) { echo ' &middot; remark: ' . htmlspecialchars($kyc['admin_remark']); }
        }
    ?></td></tr>
  </table>

  <h2>Products in category <?php echo (int)($_GET['cat'] ?? 5); ?> &mdash; why each card looks the way it does</h2>
  <p style="color:#64748b;font-size:12.5px;margin:0 0 8px">Add <code>?cat=2</code> to the address to check another category.</p>
  <table><tr><th>Product</th><th>Price</th><th>My order</th><th>Card shows</th><th>Gate</th><th>Why blocked</th><th>KYC fields</th><th>Sells as</th></tr>
  <?php foreach ($rows as $r): ?>
  <tr>
    <td><?php echo htmlspecialchars($r['title']); ?></td>
    <td>&#8377;<?php echo number_format((float)$r['price'], 2); ?></td>
    <td><?php echo htmlspecialchars($r['order_status']); ?></td>
    <td class="<?php echo $r['card'] === 'PURCHASED' ? 'warn' : ($r['card'] === 'buyable' ? 'good' : ''); ?>"><?php echo htmlspecialchars($r['card']); ?></td>
    <td class="<?php echo (isset($r['gate']) && $r['gate'] !== 'OK') ? 'bad' : 'good'; ?>"><?php echo htmlspecialchars($r['gate'] ?? '—'); ?></td>
    <td><?php echo htmlspecialchars($r['why'] ?? '—'); ?></td>
    <td style="font-size:11.5px"><?php echo htmlspecialchars($r['need'] ?? '—'); ?></td>
    <td><?php echo htmlspecialchars($r['sells'] ?? '—'); ?></td>
  </tr>
  <?php endforeach; ?>
  </table>
<?php endif; ?>

<h2>4 &middot; One product&rsquo;s picture</h2>
<p style="color:#64748b;font-size:12.5px;margin:0 0 8px">Add <code>?pid=127</code> to the address to inspect a particular product.</p>
<?php
$pid = isset($_GET['pid']) ? (int)$_GET['pid'] : 0;
if ($pid > 0):
    $pr = $db->select("SELECT id, title, is_img, icon_class FROM seller_services WHERE id = ?", [$pid]);
    $pr = $pr[0] ?? null;
    if (!$pr):
        echo '<p class="bad">No product with id ' . $pid . '.</p>';
    else:
        $th = function_exists('buy_thumb') ? buy_thumb($pr) : null;
        $onDisk = $pr['icon_class'] !== '' ? file_exists(__DIR__ . '/' . ltrim($pr['icon_class'], '/')) : false;
?>
<table>
  <tr><th>Product</th><td><?php echo htmlspecialchars($pr['title']); ?> (id <?php echo (int)$pr['id']; ?>)</td></tr>
  <tr><th><code>is_img</code></th><td><?php echo (int)$pr['is_img']; ?></td></tr>
  <tr><th><code>icon_class</code></th><td><code><?php echo htmlspecialchars($pr['icon_class']); ?></code></td></tr>
  <tr><th>File on the server?</th><td><?php echo yn($onDisk); ?> &mdash; <code><?php echo htmlspecialchars(__DIR__ . '/' . $pr['icon_class']); ?></code></td></tr>
  <tr><th><code>buy_thumb()</code> exists?</th><td><?php echo yn(function_exists('buy_thumb')); ?>
      <?php if (!function_exists('buy_thumb')): ?><span class="bad">&larr; the new includes/purchase.php has NOT been uploaded</span><?php endif; ?></td></tr>
  <tr><th><code>buy_thumb()</code> says</th><td><?php echo $th ? ('img = <code>' . htmlspecialchars($th['img']) . '</code> &middot; icon = <code>' . htmlspecialchars($th['icon']) . '</code>') : '&mdash;'; ?></td></tr>
  <tr><th>Rendered here</th><td style="background:#0b1220">
      <?php if ($th && $th['img']): ?>
        <img src="<?php echo htmlspecialchars($th['img']); ?>" alt="broken" style="width:90px;height:90px;object-fit:contain;background:#fff;border-radius:16px;padding:8px">
      <?php else: ?>
        <i class="fa <?php echo htmlspecialchars($th['icon'] ?? ''); ?>" style="color:#fff">(icon: <?php echo htmlspecialchars($th['icon'] ?? ''); ?>)</i>
      <?php endif; ?>
      <span style="color:#94a3b8;font-size:12px;margin-left:10px">If this box is white/blank, the browser cannot load that path.</span>
  </td></tr>
</table>
<?php endif; endif; ?>

<div class="note"><b>Delete <code>livecheck.php</code> from the server once you have sent me this page.</b> It shows account details and should not stay up.</div>
</div></body></html>
