<?php
/* ============================================================================
   Migration — Sidebar Restructure + Refer & Earn buttons
                 + Block sellers from ADDING Government Portal services

   Run ONCE:  https://yourdomain.com/msimigration.php   (delete after)

   THIS SCRIPT ADDS ONE NEW COLUMN:
       service_categories.seller_can_add  TINYINT(1) DEFAULT 1
       -> set to 0 for "Government Portals"

   Meaning: sellers can still SEE, USE and SELL those services, but the
   "Add New Service" button and the add form are blocked for that category.
   Admin can toggle this per category from Admin > Services.

   It also verifies:
     1. users.mobile / call_number / whatsapp_number exist
     2. contact coverage for the Refer & Earn Call / WhatsApp buttons
     3. every page the new sidebar links to is present
   ============================================================================ */
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';

header('Content-Type: text/html; charset=utf-8');
?><!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Sidebar &amp; Refer Buttons — Migration</title>
<style>
 body{font-family:system-ui,-apple-system,sans-serif;max-width:900px;margin:36px auto;padding:0 20px;color:#0f172a;line-height:1.65}
 h2{border-bottom:3px solid #6366f1;padding-bottom:10px} h3{margin-top:30px;color:#334155;border-left:4px solid #6366f1;padding-left:10px}
 p{margin:4px 0;font-size:14px} code{background:#f1f5f9;padding:2px 6px;border-radius:4px;font-size:12.5px}
 table{width:100%;border-collapse:collapse;margin:10px 0;font-size:13px}
 th,td{padding:7px 10px;border-bottom:1px solid #e2e8f0;text-align:left}
 th{background:#f8fafc;font-size:11px;text-transform:uppercase;letter-spacing:.05em;color:#64748b}
 .box{padding:16px 20px;border-radius:12px;margin:22px 0;font-size:14px}
 .ok{background:#ecfdf5;border:1px solid #a7f3d0;color:#065f46}
 .info{background:#eff6ff;border:1px solid #bfdbfe;color:#1e3a8a}
 .bad{background:#fef2f2;border:1px solid #fecaca;color:#991b1b}
 @media(max-width:640px){body{margin:20px auto}th,td{padding:6px}}
</style></head><body>
<h2>Migration — Sidebar Restructure &amp; Refer / Earn Buttons</h2>

<div class="box info">
<b>New column added by this script:</b> <code>service_categories.seller_can_add</code> (TINYINT, default 1).<br>
It is set to <b>0</b> for <b>Government Portals</b>, which stops sellers from submitting a new service
request in that category. Sellers can still <b>use</b> and <b>sell</b> everything already listed there.<br><br>
The Refer &amp; Earn Call / WhatsApp buttons need no new columns — they use
<code>users.mobile</code>, <code>users.call_number</code> and <code>users.whatsapp_number</code>,
which this script simply verifies.
</div>
<?php

$conn = $db->getConnection();
$ok = 0; $skip = 0; $fail = 0;

/* ==========================================================================
   0. NEW COLUMN — service_categories.seller_can_add
   ========================================================================== */
echo "<h3>0. Seller &ldquo;can add&rdquo; permission</h3><table><tr><th>Step</th><th>Result</th></tr>";
try {
    $r = $conn->query("SHOW COLUMNS FROM service_categories LIKE 'seller_can_add'");
    if ($r && $r->num_rows > 0) {
        $skip++;
        echo "<tr><td><code>service_categories.seller_can_add</code></td><td style='color:#059669'>&#10003; already exists</td></tr>";
    } else {
        $conn->query("ALTER TABLE service_categories ADD COLUMN seller_can_add TINYINT(1) NOT NULL DEFAULT 1 AFTER show_to_seller");
        $ok++;
        echo "<tr><td><code>service_categories.seller_can_add</code></td><td style='color:#d97706'>&#10003; column created (default 1 = allowed)</td></tr>";
    }
} catch (\Throwable $e) {
    $fail++;
    echo "<tr><td><code>service_categories.seller_can_add</code></td><td style='color:#dc2626'>&#10007; " . htmlspecialchars($e->getMessage()) . "</td></tr>";
}

/* Lock Government Portals — matched by key first, then by id, then by title */
try {
    $conn->query("UPDATE service_categories SET seller_can_add = 0
                  WHERE category_key = 'cat_gov_portals' OR id = 1 OR title LIKE '%Government Portal%'");
    $n = $conn->affected_rows;
    echo "<tr><td>Lock <b>Government Portals</b> for seller submissions</td><td style='color:#059669'>&#10003; done"
       . ($n > 0 ? " ($n row" . ($n > 1 ? 's' : '') . " updated)" : " (already locked)") . "</td></tr>";
} catch (\Throwable $e) {
    $fail++;
    echo "<tr><td>Lock Government Portals</td><td style='color:#dc2626'>&#10007; " . htmlspecialchars($e->getMessage()) . "</td></tr>";
}
echo "</table>";

/* Show the resulting permission table */
try {
    $rows = $db->select("SELECT id, title, show_to_seller, seller_can_add FROM service_categories ORDER BY display_order ASC");
    echo "<table><tr><th>#</th><th>Category</th><th>Shown to seller</th><th>Seller can ADD?</th></tr>";
    foreach ($rows as $c) {
        $canAdd = (int)$c['seller_can_add'] === 1;
        echo "<tr><td>" . (int)$c['id'] . "</td><td><b>" . htmlspecialchars($c['title']) . "</b></td>"
           . "<td>" . ((int)$c['show_to_seller'] === 1 ? 'Yes' : 'No') . "</td>"
           . "<td style='color:" . ($canAdd ? '#059669' : '#d97706') . ";font-weight:700'>"
           . ($canAdd ? '&#10003; Allowed' : '&#128274; Blocked (use &amp; sell only)') . "</td></tr>";
    }
    echo "</table>";
    echo "<p style='font-size:13px;color:#64748b'>You can change any of these later from <b>Admin &gt; Services &gt; edit a Main Category</b> &mdash; the new tick box <i>&ldquo;Allow Sellers to add a new service here&rdquo;</i>.</p>";
} catch (\Throwable $e) {
    echo "<p style='color:#dc2626'>" . htmlspecialchars($e->getMessage()) . "</p>";
}

/* ==========================================================================
   1. Contact columns on `users` (safety net only)
   ========================================================================== */
echo "<h3>1. Contact columns on <code>users</code></h3><table><tr><th>Column</th><th>Result</th></tr>";
foreach ([
    'mobile'          => "VARCHAR(15) NOT NULL DEFAULT ''",
    'call_number'     => "VARCHAR(20) DEFAULT NULL",
    'whatsapp_number' => "VARCHAR(20) DEFAULT NULL",
] as $col => $def) {
    try {
        $r = $conn->query("SHOW COLUMNS FROM users LIKE '$col'");
        if ($r && $r->num_rows > 0) {
            $skip++;
            echo "<tr><td><code>users.$col</code></td><td style='color:#059669'>&#10003; already exists</td></tr>";
        } else {
            $conn->query("ALTER TABLE users ADD COLUMN $col $def");
            $ok++;
            echo "<tr><td><code>users.$col</code></td><td style='color:#d97706'>&#10003; created (was missing)</td></tr>";
        }
    } catch (\Throwable $e) {
        $fail++;
        echo "<tr><td><code>users.$col</code></td><td style='color:#dc2626'>&#10007; " . htmlspecialchars($e->getMessage()) . "</td></tr>";
    }
}
echo "</table>";

/* ==========================================================================
   2. How many users can actually be contacted
   ========================================================================== */
echo "<h3>2. Contact coverage</h3><table><tr><th>Check</th><th>Count</th></tr>";
foreach ([
    "SELECT COUNT(*) n FROM users" => 'total users',
    "SELECT COUNT(*) n FROM users WHERE mobile IS NOT NULL AND mobile <> ''" => 'have a mobile number',
    "SELECT COUNT(*) n FROM users WHERE call_number IS NOT NULL AND call_number <> ''" => 'have a separate call number',
    "SELECT COUNT(*) n FROM users WHERE whatsapp_number IS NOT NULL AND whatsapp_number <> ''" => 'have a separate WhatsApp number',
    "SELECT COUNT(*) n FROM users WHERE referred_by IS NOT NULL AND referred_by > 0" => 'users who came through a referral',
] as $sql => $label) {
    try { $r = $db->select($sql); echo "<tr><td>$label</td><td><b>" . (!empty($r) ? $r[0]['n'] : 0) . "</b></td></tr>"; }
    catch (\Throwable $e) { echo "<tr><td>$label</td><td style='color:#dc2626'>" . htmlspecialchars($e->getMessage()) . "</td></tr>"; }
}
echo "</table>";
echo "<p style='font-size:13px;color:#64748b'>On the Refer &amp; Earn page, a referred user with no number at all shows a dash instead of buttons.
WhatsApp uses the WhatsApp number, falling back to the mobile; a plain 10-digit number is automatically prefixed with <code>91</code>.</p>";

/* ==========================================================================
   3. Every page the new sidebar points at
   ========================================================================== */
echo "<h3>3. Sidebar destinations</h3>";

$member_pages = [
    'Dashboard'       => 'dashboard.php',
    'Profile'         => 'profile.php',
    'Wallet'          => 'wallet.php',
    'Earning Report'  => 'earning_report.php',
    'Services'        => 'category.php',
    'Order History'   => 'orders.php',
    'My Subscription' => 'subscription.php',
    'Refer & Earn'    => 'refer.php',
    'Helpdesk'        => 'helpdesk.php',
];
$seller_pages = [
    'Dashboard'       => 'seller/index.php',
    'Profile'         => 'seller/profile.php',
    'Wallet'          => 'seller/wallet.php',
    'Earning Report'  => 'seller/earning_report.php',
    'Services'        => 'category.php',
    'Order History'   => 'orders.php',
    'My Service'      => 'seller/services.php',
    'Customer Orders' => 'seller/orders.php',
    'Sell Report'     => 'seller/reports.php',
    'My Subscription' => 'subscription.php',
    'Refer & Earn'    => 'refer.php',
    'Helpdesk'        => 'seller/helpdesk.php',
];

foreach ([['Member panel', $member_pages], ['Seller panel', $seller_pages]] as $set) {
    echo "<h4 style='margin:16px 0 4px;color:#475569'>{$set[0]}</h4><table><tr><th>#</th><th>Menu item</th><th>File</th><th>Status</th></tr>";
    $i = 0;
    foreach ($set[1] as $label => $file) {
        $i++;
        $exists = file_exists(__DIR__ . '/' . $file);
        if (!$exists) $fail++;
        echo "<tr><td>$i</td><td><b>" . htmlspecialchars($label) . "</b></td><td><code>" . htmlspecialchars($file) . "</code></td><td style='color:"
           . ($exists ? '#059669' : '#dc2626') . "'>" . ($exists ? '&#10003; present' : '&#10007; MISSING — upload it') . "</td></tr>";
    }
    echo "</table>";
}

/* ==========================================================================
   4. Are the updated files actually on this server?
   ========================================================================== */
echo "<h3>4. Updated files on this server</h3><table><tr><th>File</th><th>Status</th></tr>";
foreach ([
    'includes/theme.php'   => "'Sell Report'",
    'refer.php'            => 'fa-whatsapp',
    'seller/services.php'  => 'seller_can_add_to',
    'admin/services.php'   => "name=\"seller_can_add\"",
] as $f => $marker) {
    $path = __DIR__ . '/' . $f;
    if (!file_exists($path)) {
        $fail++;
        echo "<tr><td><code>$f</code></td><td style='color:#dc2626'>&#10007; file missing</td></tr>";
        continue;
    }
    $has = strpos((string)@file_get_contents($path), $marker) !== false;
    if (!$has) $fail++;
    echo "<tr><td><code>$f</code></td><td style='color:" . ($has ? '#059669' : '#dc2626') . "'>"
       . ($has ? '&#10003; new version uploaded' : '&#10007; OLD version — re-upload this file') . "</td></tr>";
}
echo "</table>";
?>

<?php if ($fail === 0): ?>
<div class="box ok"><b>&#10003; All good</b> — <?php echo $ok; ?> column(s) created, <?php echo $skip; ?> already existed, nothing failed.<br><br>
<b>What changed in this update</b><br>
• <b>Member sidebar</b>: Dashboard · Profile · Wallet · Earning Report · Services · Order History · My Subscription · Refer &amp; Earn · Helpdesk<br>
• <b>Seller sidebar</b>: Dashboard · Profile · Wallet · Earning Report · Services · Order History · My Service · Customer Orders · Sell Report · My Subscription · Refer &amp; Earn · Helpdesk<br>
• <b>Refer &amp; Earn</b>: a green WhatsApp share button beside Copy Link, and Call + WhatsApp buttons on every referred user row.<br>
• <b>Government Portals</b>: sellers can no longer submit an add request there. The Add button is replaced by a locked badge, the category is removed from the add form's picker, and the POST is rejected server-side even if someone forges it. Using and selling those services is unchanged.</div>
<?php else: ?>
<div class="box bad"><b>&#10007; <?php echo $fail; ?> problem(s) found</b> — see the red rows above. Most likely a file still needs uploading.</div>
<?php endif; ?>

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