<?php
/* ============================================================================
   SERVER CHECK — run this on the live server to find out exactly what is
   missing or stale.  It changes nothing; it only reports.

       https://yourdomain.com/servercheck.php

   Delete this file once everything is green.
   ============================================================================ */
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';

$conn = $db->getConnection();

/* Files that must exist, with a marker string that proves the NEW version was
   uploaded (not the old one sitting in cache or a half-finished FTP transfer). */
$files = [
    // --- NEW files (must exist at all) ---
    'includes/wallet.php'             => 'wallet_earning_categories',
    'includes/credentials.php'        => 'function cred_render_id_card',
    'includes/earning_view.php'       => 'earning_user_type',
    'earningsourcemigration.php'      => 'ref_sub_l1',
    'admin/wallet_history.php'        => 'Wallet History',
    'earning_report.php'              => 'earning_render',
    'seller/earning_report.php'       => 'earning_render',
    'newmigration.php'                => 'wallet_ledger',
    'newproductmigration.php'         => 'product_areas',
    'includes/bank.php'               => 'function bank_request_withdrawal',
    'includes/bank_view.php'          => 'function bank_render_to_bank',
    'admin/withdrawals.php'           => 'Bank Request Pending',
    'wallettomigration.php'           => 'withdrawal_requests',

    // --- MODIFIED files (marker proves the new version is live) ---
    'includes/shares.php'             => "'ref_sale'",
    'includes/functions.php'          => 'recordOwnDiscount',
    'includes/theme.php'              => 'wallet.php#to_bank',
    'includes/kyc.php'                => 'kyc_render_form',
    'category.php'                    => 'govt-icon',
    'wallet.php'                      => "currentTab === 'to_bank'",
    'seller/wallet.php'               => "currentTab === 'to_bank'",
    'subscription.php'                => 'distributeReferralCommission',
    'profile.php'                     => "currentTab === 'id_card'",
    'seller/profile.php'              => "currentTab === 'id_card'",
    'seller/services.php'             => 'rejection_reason',
    'admin/product_management.php'    => 'save_recruitment',
    'admin/pending_services.php'      => 'edit_then_approve',
    'admin/sellers.php'               => 'cred_issue_seller_certificate',
    'admin/wallet.php'                => 'wallet_credit',
    'admin/orders.php'                => 'wallet_credit',
    'admin/user_list.php'             => 'wallet_credit',
    'seller/index.php'                => 'wallet_credit',
    'seller/orders.php'               => 'wallet_credit',
    'add_money.php'                   => 'wallet_credit',
];

/* Admin pages that should carry the Wallet History sidebar link */
$sidebar_files = [
    'admin/commissions.php','admin/index.php','admin/orders.php','admin/pending_services.php',
    'admin/profile.php','admin/refer.php','admin/reports.php','admin/roles.php','admin/sellers.php',
    'admin/services.php','admin/settings.php','admin/staff.php','admin/tickets.php',
    'admin/transactions.php','admin/upgrade_requests.php','admin/users.php','admin/wallet.php',
];

/* Database objects the new features need */
$columns = [
    'users'           => ['bonus_wallet','is_subscribed','referred_by','pincode'],
    'seller_services' => ['seller_share_pct','subscription_discount_pct','referral_share_pct',
                          'staff_share_pct','company_share_pct','required_kyc','area_mode',
                          'rejection_reason','reviewed_by','reviewed_by_name','reviewed_at'],
    'bank_accounts'   => ['holder_name','account_number','ifsc_code','status','admin_remark'],
    'withdrawal_requests' => ['reference_no','amount','charge','net_amount','status','utr_number'],
];

/* Settings rows the withdrawal system needs */
$setting_keys = ['withdraw_enabled','withdraw_min','withdraw_max','withdraw_charge_type','withdraw_charge_value','withdraw_note'];
$tables = ['wallet_ledger','member_certificates','product_areas','product_share_ledger',
           'product_notes','product_update_history','kyc_details',
           'bank_accounts','withdrawal_requests'];

$fail = 0; $warn = 0;
function row($ok, $label, $note = '', $level = 'fail') {
    global $fail, $warn;
    if (!$ok) { if ($level === 'warn') $warn++; else $fail++; }
    $c = $ok ? '#059669' : ($level === 'warn' ? '#d97706' : '#dc2626');
    $i = $ok ? '&#10003;' : ($level === 'warn' ? '&#9888;' : '&#10007;');
    echo "<tr><td style='color:$c;width:26px;font-size:16px'>$i</td><td><code>"
       . htmlspecialchars($label) . "</code></td><td style='color:#64748b;font-size:12px'>"
       . htmlspecialchars($note) . "</td></tr>";
}
?><!DOCTYPE html><html><head><meta charset="utf-8"><title>Server Check</title>
<style>
 body{font-family:system-ui,-apple-system,sans-serif;max-width:980px;margin:36px auto;padding:0 20px;color:#0f172a}
 h2{border-bottom:3px solid #6366f1;padding-bottom:10px}
 h3{margin-top:34px;color:#334155;border-left:4px solid #6366f1;padding-left:10px}
 table{width:100%;border-collapse:collapse;margin-top:8px}
 td{padding:5px 8px;border-bottom:1px solid #f1f5f9;vertical-align:top}
 code{background:#f1f5f9;padding:2px 6px;border-radius:4px;font-size:12.5px}
 .box{padding:16px 20px;border-radius:12px;margin:22px 0;font-size:14px;line-height:1.7}
 .ok{background:#ecfdf5;border:1px solid #a7f3d0;color:#065f46}
 .bad{background:#fef2f2;border:1px solid #fecaca;color:#991b1b}
 .info{background:#eff6ff;border:1px solid #bfdbfe;color:#1e3a8a}
 ol li{margin:6px 0}
</style></head><body>
<h2>WBMCZ — Server Check</h2>
<p style="color:#64748b;font-size:14px">PHP <?php echo PHP_VERSION; ?> &nbsp;•&nbsp; <?php echo date('d M Y, h:i A'); ?></p>

<h3>1. Files uploaded &amp; up to date</h3>
<table>
<?php
foreach ($files as $f => $marker) {
    $path = __DIR__ . '/' . $f;
    if (!file_exists($path)) { row(false, $f, 'FILE MISSING — upload it'); continue; }
    $content = @file_get_contents($path);
    $ok = ($content !== false && strpos($content, $marker) !== false);
    $when = date('d M H:i', filemtime($path));
    row($ok, $f, $ok ? "ok · uploaded $when" : "OLD VERSION — re-upload (looking for \"$marker\")");
}
?>
</table>

<h3>2. Wallet History link in the admin sidebar</h3>
<table>
<?php
$miss_side = 0;
foreach ($sidebar_files as $f) {
    $path = __DIR__ . '/' . $f;
    if (!file_exists($path)) { row(false, $f, 'file missing'); $miss_side++; continue; }
    $ok = strpos((string)@file_get_contents($path), 'wallet_history.php') !== false;
    if (!$ok) $miss_side++;
    row($ok, $f, $ok ? 'link present' : 'sidebar link missing — re-upload this file', 'warn');
}
?>
</table>

<h3>3. Database tables</h3>
<table>
<?php
foreach ($tables as $t) {
    $ok = false;
    try { $r = $conn->query("SHOW TABLES LIKE '$t'"); $ok = ($r && $r->num_rows > 0); } catch (\Throwable $e) {}
    row($ok, $t, $ok ? 'exists' : 'MISSING — run the migration');
}
?>
</table>

<h3>4. Database columns</h3>
<table>
<?php
foreach ($columns as $tbl => $cols) {
    foreach ($cols as $c) {
        $ok = false;
        try { $r = $conn->query("SHOW COLUMNS FROM `$tbl` LIKE '$c'"); $ok = ($r && $r->num_rows > 0); } catch (\Throwable $e) {}
        row($ok, "$tbl.$c", $ok ? 'exists' : 'MISSING — run the migration');
    }
}
?>
</table>

<h3>4b. Withdrawal settings</h3>
<table>
<?php
foreach ($setting_keys as $k) {
    $val = null;
    try { $r = $db->select("SELECT setting_value FROM settings WHERE setting_key = ?", [$k]); if (!empty($r)) $val = $r[0]['setting_value']; }
    catch (\Throwable $e) {}
    row($val !== null, $k, $val !== null ? "= $val" : 'MISSING — run wallettomigration.php');
}
$updir = __DIR__ . '/uploads/bank/';
row(is_dir($updir), 'uploads/bank/ folder', is_dir($updir) ? (is_writable($updir) ? 'exists and writable' : 'exists but NOT WRITABLE — set 755') : 'MISSING — create it with permission 755');
?>
</table>

<h3>5. Data sanity</h3>
<table>
<?php
$checks = [
    "SELECT COUNT(*) n FROM wallet_ledger"                        => 'wallet_ledger rows (0 = migration backfill not run)',
    "SELECT COUNT(*) n FROM member_certificates"                  => 'certificates issued',
    "SELECT COUNT(*) n FROM users WHERE user_type='seller'"       => 'sellers on the platform',
    "SELECT COUNT(*) n FROM product_areas"                        => 'serviceable pincodes configured',
    "SELECT COUNT(*) n FROM seller_services WHERE status=0"       => 'services pending review',
    "SELECT COUNT(*) n FROM seller_services WHERE status=2"       => 'services rejected',
    "SELECT COUNT(*) n FROM bank_accounts WHERE status=0"         => 'bank accounts awaiting verification',
    "SELECT COUNT(*) n FROM bank_accounts WHERE status=1"         => 'bank accounts verified',
    "SELECT COUNT(*) n FROM withdrawal_requests WHERE status='pending'" => 'withdrawals awaiting payout',
];
foreach ($checks as $sql => $label) {
    try {
        $r = $conn->query($sql);
        $n = $r ? (int)$r->fetch_assoc()['n'] : 0;
        row(true, $label, "= $n");
    } catch (\Throwable $e) { row(false, $label, 'query failed: ' . $e->getMessage()); }
}
// Sellers without a certificate
try {
    $r = $conn->query("SELECT COUNT(*) n FROM users u WHERE u.user_type='seller'
                       AND NOT EXISTS (SELECT 1 FROM member_certificates c WHERE c.user_id=u.id)");
    $n = $r ? (int)$r->fetch_assoc()['n'] : 0;
    row($n === 0, 'sellers WITHOUT a certificate', $n === 0 ? 'all sellers covered' : "$n seller(s) — re-run newmigration.php", 'warn');
} catch (\Throwable $e) {}
?>
</table>

<h3>6. Caching</h3>
<table>
<?php
$opc = function_exists('opcache_get_status');
$st  = $opc ? @opcache_get_status(false) : null;
$on  = ($st && !empty($st['opcache_enabled']));
row(!$on, 'PHP OPcache', $on
    ? 'ENABLED — this is very likely why your changes are not showing. Clear it (see below).'
    : ($opc ? 'installed but disabled — fine' : 'not installed — fine'), 'warn');
if ($on && isset($_GET['clearcache'])) {
    @opcache_reset();
    echo "<tr><td style='color:#059669'>&#10003;</td><td colspan='2'><b>OPcache has been reset.</b> Reload your pages now.</td></tr>";
} elseif ($on) {
    echo "<tr><td></td><td colspan='2'><a href='servercheck.php?clearcache=1' style='color:#dc2626;font-weight:700'>&rarr; Click here to clear OPcache now</a></td></tr>";
}
?>
</table>

<?php if ($fail === 0 && $warn === 0): ?>
<div class="box ok"><b>&#10003; Everything is in place.</b><br>
If a page still looks unchanged, hard-refresh your browser with <b>Ctrl + Shift + R</b> (or <b>Cmd + Shift + R</b>).</div>
<?php else: ?>
<div class="box bad"><b>&#10007; <?php echo $fail; ?> problem(s)</b><?php if ($warn): ?> and <b><?php echo $warn; ?> warning(s)</b><?php endif; ?> found — see the red and orange rows above.</div>
<?php endif; ?>

<div class="box info">
<b>If things still don't show, work through this in order:</b>
<ol>
  <li><b>Re-upload anything marked red above.</b> The <code>includes/</code> folder is the one most often missed — the menus, wallet engine, certificate and report all live there.</li>
  <li><b>Run both migrations, in this order:</b><br>
      <code>newproductmigration.php</code> &nbsp;then&nbsp; <code>newmigration.php</code><br>
      Missing tables/columns in sections 3 and 4 mean this step was skipped.</li>
  <li><b>Clear OPcache</b> using the link in section 6 (or restart PHP-FPM / Apache from your hosting panel).</li>
  <li><b>Hard-refresh the browser</b> — Ctrl + Shift + R. Tailwind and Alpine are cached aggressively.</li>
  <li><b>Check your FTP uploaded to the right folder</b> — the site root must be the folder containing <code>index.php</code> and <code>config.php</code>, and <code>includes/</code> must sit beside it.</li>
  <li><b>Check file permissions</b> — uploaded PHP files should be <code>644</code>, folders <code>755</code>.</li>
</ol>
</div>

<p style="color:#dc2626;font-weight:700;margin-top:26px">Delete servercheck.php from the server once everything is green.</p>
</body></html>
