<?php
/* ============================================================================
   WBMCZ — SMS MIGRATION  (OTP for registration and password reset)
   Run this ONCE on the live server:   https://wbmcz.online/smsmigration.php

   What it does
     1. otp_codes   the one-time codes: hashed, timed, attempt-limited
     2. sms_log     every text that left the site, and every one that failed
     3. settings    the HSPSMS account details, the on/off switches and the
                    three message templates — all editable afterwards under
                    Admin → Website Settings → SMS & OTP

   Your API key is written in for you. The Sender ID is left blank on purpose:
   put your DLT-approved header in on the settings screen, and until you do,
   the system stays in TEST MODE — the code appears on the screen instead of
   being texted, so you can try the whole flow straight away.

   Safe to run more than once — nothing already set is overwritten.
   DELETE THIS FILE after a successful run.
   ============================================================================ */

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

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

if (!@is_file(__DIR__ . '/includes/sms.php')) {
    $log[] = ['fail', 'includes/sms.php', 'Upload includes/sms.php first, then open this page again.'];
} else {
    require_once __DIR__ . '/includes/sms.php';
}

function smsm_table_exists($conn, $t) {
    try { $r = $conn->query("SHOW TABLES LIKE '$t'"); return $r && $r->num_rows > 0; }
    catch (\Throwable $e) { return false; }
}

if (function_exists('sms_ensure_schema')) {

    /* ---- 1 & 2 : the two tables ---- */
    $before = [];
    foreach (['otp_codes', 'sms_log'] as $t) { $before[$t] = smsm_table_exists($conn, $t); }
    sms_ensure_schema($db);
    foreach ($before as $t => $had) {
        $log[] = $had ? ['ok', $t, 'table already exists'] : ['add', $t, 'table created'];
    }

    /* ---- 3 : the settings ---- */
    $seed = [
        'sms_enabled'          => '1',
        'sms_test_mode'        => '1',                     // safe until the header is approved
        'sms_api_url'          => 'http://sms.hspsms.com',
        'sms_username'         => 'esrafilmilla455',
        'sms_apikey'           => 'fc7e7926-8528-420a-9157-6a06195b0bc1',
        'sms_sender_id'        => '',                      // your DLT header goes here
        'sms_type'             => 'TRANS',
        'sms_entity_id'        => '',
        'otp_length'           => '6',
        'otp_expiry_minutes'   => '10',
        'otp_max_attempts'     => '5',
        'otp_resend_seconds'   => '60',
        'otp_max_per_day'      => '10',
        'otp_register_enabled' => '1',
        'otp_reset_enabled'    => '1',
        'reset_email_enabled'  => '1',
        'sms_welcome_enabled'  => '1',
        'sms_tpl_otp_register' => '{otp} is your OTP to verify your mobile number at {company}. Valid for {minutes} minutes. Do not share it with anyone.',
        'sms_tpl_otp_reset'    => '{otp} is your OTP to reset your {company} password. Valid for {minutes} minutes. Do not share it with anyone.',
        'sms_tpl_welcome'      => 'Congratulations {name}! Your {company} account is ready. User ID: {userid}. Referral code: {refcode}. Login at {site}',
    ];

    $added = 0; $kept = 0;
    foreach ($seed as $k => $v) {
        try {
            $has = $db->select("SELECT id, setting_value FROM settings WHERE setting_key = ?", [$k]);
            if (!empty($has)) { $kept++; continue; }          // never overwrite what is already there
            $db->insert("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?)", [$k, $v]);
            $added++;
        } catch (\Throwable $e) { $log[] = ['fail', 'settings.' . $k, $e->getMessage()]; }
    }
    $log[] = ['add', 'settings', "$added new setting(s) written" . ($kept ? ", $kept already there and left alone" : '')];

    /* ---- a note about what still needs doing ---- */
    $sender = '';
    try { $r = $db->select("SELECT setting_value FROM settings WHERE setting_key = 'sms_sender_id'"); $sender = trim((string)($r[0]['setting_value'] ?? '')); }
    catch (\Throwable $e) {}
    if ($sender === '') {
        $log[] = ['skip', 'sms_sender_id', 'still blank — the system stays in test mode until you fill it in'];
    } else {
        $log[] = ['ok', 'sms_sender_id', 'set to ' . $sender];
    }

    /* ---- users.mobile should be unique-ish; make sure the lookup is fast ---- */
    try {
        $r = $conn->query("SHOW INDEX FROM users WHERE Key_name = 'idx_users_mobile'");
        if ($r && $r->num_rows === 0) {
            $conn->query("ALTER TABLE users ADD INDEX idx_users_mobile (mobile)");
            $log[] = ['add', 'users.idx_users_mobile', 'index added so OTP lookups stay quick'];
        } else {
            $log[] = ['ok', 'users.idx_users_mobile', 'already present'];
        }
    } catch (\Throwable $e) { $log[] = ['skip', 'users.idx_users_mobile', $e->getMessage()]; }
}

$fails = 0; $adds = 0;
foreach ($log as $l) { if ($l[0] === 'fail') $fails++; if ($l[0] === 'add') $adds++; }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SMS Migration — OTP Verification</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-slate-100 p-6 font-sans">
    <div class="max-w-3xl mx-auto bg-white rounded-2xl shadow p-6 border border-slate-200">
        <h1 class="text-2xl font-extrabold text-slate-800 mb-1">SMS Migration — OTP Verification</h1>
        <p class="text-sm text-slate-500 mb-5">Database: <b><?php echo DB_NAME; ?></b> &middot; one-time codes, the SMS log, and the HSPSMS settings</p>

        <div class="mb-5 rounded-xl px-4 py-3 <?php echo $fails ? 'bg-rose-50 text-rose-700 border border-rose-200' : 'bg-emerald-50 text-emerald-700 border border-emerald-200'; ?>">
            <?php echo $fails ? "Finished with $fails error(s) — see the rows marked FAIL."
                              : "Migration completed successfully — $adds change(s) applied."; ?>
        </div>

        <table class="w-full text-sm border-collapse">
            <thead>
                <tr class="bg-slate-50 text-slate-500 text-xs uppercase tracking-wider">
                    <th class="text-left py-2 px-3">Result</th>
                    <th class="text-left py-2 px-3">Target</th>
                    <th class="text-left py-2 px-3">Detail</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-100">
            <?php foreach ($log as $l):
                $cls = ['ok' => 'text-slate-500', 'add' => 'text-emerald-600', 'skip' => 'text-amber-600', 'fail' => 'text-rose-600'][$l[0]] ?? '';
            ?>
                <tr>
                    <td class="py-2 px-3 font-bold uppercase <?php echo $cls; ?>"><?php echo $l[0]; ?></td>
                    <td class="py-2 px-3 font-mono text-slate-700 text-xs"><?php echo htmlspecialchars($l[1]); ?></td>
                    <td class="py-2 px-3 text-slate-500 text-xs"><?php echo htmlspecialchars($l[2]); ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>

        <div class="mt-6 text-xs text-slate-600 space-y-2 bg-amber-50 border border-amber-200 rounded-xl p-4">
            <p class="font-bold text-amber-800 text-sm">Two things to do next</p>
            <p><b>1.</b> Open <b>Admin &rarr; Website Settings &rarr; SMS &amp; OTP</b> and put your DLT-approved
               <b>Sender ID</b> in (the 6-character header from your HSPSMS panel, under Setting &rarr; Sender ID).</p>
            <p><b>2.</b> Paste your three DLT-approved template texts into the same screen, then switch
               <b>Test mode</b> off. Press <b>Send a test SMS</b> to your own number to be sure.</p>
            <p class="text-slate-500">Until you do, the site keeps working — the code simply appears on the screen
               instead of arriving by text, so registration and password reset can be tried right now.</p>
        </div>

        <p class="mt-4 text-xs text-rose-600 font-bold">Delete smsmigration.php from the server once this page shows &ldquo;completed successfully&rdquo;.</p>
    </div>
</body>
</html>
