<?php
/* ============================================================================
   WBMCZ ADMIN — SMS & OTP
   ----------------------------------------------------------------------------
   The gateway details, the on/off switches, the rules a one-time code follows,
   and the three message templates — all on one screen, with a test button so
   you can prove it works before letting real members near it.
   ============================================================================ */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/Language.php';
require_once __DIR__ . '/../includes/rbac.php';
require_once __DIR__ . '/../includes/sms.php';
require_once __DIR__ . '/../includes/activity.php';

if (!isLoggedIn() || !isAdmin()) { redirect('login.php'); }

/* the detailed access system, when it is on the server */
if (@is_file(__DIR__ . '/../includes/acl.php')) {
    require_once __DIR__ . '/../includes/acl.php';
    acl_ensure_schema($db);
    acl_guard(['website.sms', 'website.general']);
} elseif (!hasPermission('manage_settings')) {
    die('Access Denied: You do not have permission to change site settings.');
}

sms_ensure_schema($db);

$lang         = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id      = (int)$_SESSION['user_id'];

$user_data = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user      = !empty($user_data) ? $user_data[0] : null;
if (!$user) { session_destroy(); redirect('login.php'); }

$company_name = getSetting('company_name', 'WBMCZ');
$flash_ok  = $_SESSION['flash_success'] ?? ''; unset($_SESSION['flash_success']);
$flash_err = $_SESSION['flash_error']   ?? ''; unset($_SESSION['flash_error']);

$test_result = null;
$balance     = '';

/* ============================================================================
   SAVE
   ============================================================================ */
if (isset($_POST['save_sms'])) {
    $text = ['sms_api_url', 'sms_username', 'sms_apikey', 'sms_sender_id', 'sms_type', 'sms_entity_id',
             'sms_tpl_otp_register', 'sms_tpl_otp_reset', 'sms_tpl_welcome'];
    foreach ($text as $k) {
        if (isset($_POST[$k])) { sms_cfg_set($k, trim((string)$_POST[$k])); }
    }

    $nums = ['otp_length' => [4, 8], 'otp_expiry_minutes' => [1, 60], 'otp_max_attempts' => [1, 10],
             'otp_resend_seconds' => [0, 600], 'otp_max_per_day' => [0, 100]];
    foreach ($nums as $k => $range) {
        if (isset($_POST[$k])) {
            $v = max($range[0], min($range[1], (int)$_POST[$k]));
            sms_cfg_set($k, (string)$v);
        }
    }

    foreach (['sms_enabled', 'sms_test_mode', 'otp_register_enabled', 'otp_reset_enabled',
              'reset_email_enabled', 'sms_welcome_enabled'] as $k) {
        sms_cfg_set($k, !empty($_POST[$k]) ? '1' : '0');
    }

    activity_log($db, 'update', 'Website Settings', 'SMS & OTP settings saved');
    $_SESSION['flash_success'] = 'SMS and OTP settings saved.';
    redirect('sms_settings.php');
}

/* ============================================================================
   SEND A TEST
   ============================================================================ */
if (isset($_POST['send_test'])) {
    $to  = sms_clean_mobile($_POST['test_mobile'] ?? '');
    $txt = trim((string)($_POST['test_message'] ?? ''));
    if ($txt === '') {
        $txt = sms_render(sms_cfg('sms_tpl_otp_register'), ['otp' => '123456']);
    }
    if (!sms_valid_mobile($to)) {
        $_SESSION['flash_error'] = 'Please give a correct 10 digit mobile number to test with.';
        redirect('sms_settings.php');
    }
    $res = sms_send($to, $txt, 'test', $user_id);
    activity_log($db, 'send', 'Website Settings', 'Test SMS to ' . $to . ' — ' . ($res['ok'] ? 'ok' : 'failed'));

    $_SESSION['sms_test_result'] = $res;
    $_SESSION['sms_test_to']     = $to;
    redirect('sms_settings.php#test');
}
if (!empty($_SESSION['sms_test_result'])) {
    $test_result = $_SESSION['sms_test_result'];
    $test_to     = $_SESSION['sms_test_to'] ?? '';
    unset($_SESSION['sms_test_result'], $_SESSION['sms_test_to']);
}

/* ============================================================================
   THE WORDING THE OPERATOR HAS ALREADY APPROVED

   A transactional text whose wording is not a registered DLT template is
   accepted by the gateway, billed, and then quietly dropped by the operator —
   it comes back as "expired / undelivered", never as a rejection. So the site
   sends the body HSPSMS has approved under this account's header, with our two
   values dropped into its two {#var#} slots and every other word untouched.
   ============================================================================ */
$DLT_REGISTER = '{otp} is the OTP for {company}. Please do not share this OTP with anyone. This SMS has been sent from GuestRAR.';
$DLT_RESET    = '{otp} is the OTP for {company} password reset. Please do not share this OTP with anyone. This SMS has been sent from GuestRAR.';

if (isset($_POST['apply_dlt'])) {
    sms_cfg_set('sms_tpl_otp_register', $DLT_REGISTER);
    sms_cfg_set('sms_tpl_otp_reset',    $DLT_RESET);
    sms_cfg_set('sms_welcome_enabled',  '0');   // it has no approved template of its own yet
    activity_log($db, 'update', 'Website Settings', 'Applied the approved DLT wording to the OTP templates');
    $_SESSION['flash_success'] = 'The approved DLT wording is in. The welcome SMS is switched off until it has a template of its own.';
    redirect('sms_settings.php');
}

/* ============================================================================
   DELIVERY REPORT — did the operator actually hand it over?
   ============================================================================ */
$dlr = null; $dlr_id = '';
if (isset($_POST['check_dlr'])) {
    $_SESSION['sms_dlr']    = sms_dlr($_POST['dlr_msgid'] ?? '');
    $_SESSION['sms_dlr_id'] = trim((string)($_POST['dlr_msgid'] ?? ''));
    redirect('sms_settings.php#dlr');
}
if (!empty($_SESSION['sms_dlr'])) {
    $dlr = $_SESSION['sms_dlr']; $dlr_id = $_SESSION['sms_dlr_id'] ?? '';
    unset($_SESSION['sms_dlr'], $_SESSION['sms_dlr_id']);
}

/* ============================================================================
   CREDIT CHECK
   ============================================================================ */
if (isset($_POST['check_balance'])) {
    $b = sms_balance();
    $_SESSION['flash_success'] = $b !== ''
        ? 'The gateway says your remaining credit is: ' . $b
        : 'The gateway did not answer with a credit figure — check the username and API key.';
    redirect('sms_settings.php');
}

/* ============================================================================
   CLEAR OLD LOGS
   ============================================================================ */
if (isset($_POST['purge_logs'])) {
    $days = max(1, (int)($_POST['purge_days'] ?? 30));
    try {
        $db->insert("DELETE FROM sms_log   WHERE created_at < DATE_SUB(NOW(), INTERVAL ? DAY)", [$days]);
        $db->insert("DELETE FROM otp_codes WHERE created_at < DATE_SUB(NOW(), INTERVAL ? DAY)", [$days]);
        $_SESSION['flash_success'] = "Anything older than {$days} days has been cleared.";
    } catch (\Throwable $e) { $_SESSION['flash_error'] = 'Nothing to clear.'; }
    redirect('sms_settings.php');
}

/* ============================================================================
   DATA
   ============================================================================ */
$cfg = sms_defaults();
try {
    foreach ($db->select("SELECT setting_key, setting_value FROM settings") as $r) {
        if (array_key_exists($r['setting_key'], $cfg)) { $cfg[$r['setting_key']] = $r['setting_value']; }
    }
} catch (\Throwable $e) {}

$stats = ['sent' => 0, 'failed' => 0, 'skipped' => 0, 'today' => 0, 'otp_today' => 0, 'otp_ok' => 0];
try {
    $r = $db->select("SELECT
            SUM(status='sent') s, SUM(status='failed') f, SUM(status='skipped') k,
            SUM(DATE(created_at)=CURDATE()) t FROM sms_log");
    $stats['sent'] = (int)($r[0]['s'] ?? 0); $stats['failed'] = (int)($r[0]['f'] ?? 0);
    $stats['skipped'] = (int)($r[0]['k'] ?? 0); $stats['today'] = (int)($r[0]['t'] ?? 0);
} catch (\Throwable $e) {}
try {
    $r = $db->select("SELECT COUNT(*) c, SUM(verified=1) v FROM otp_codes WHERE DATE(created_at)=CURDATE()");
    $stats['otp_today'] = (int)($r[0]['c'] ?? 0); $stats['otp_ok'] = (int)($r[0]['v'] ?? 0);
} catch (\Throwable $e) {}

$logs = [];
try { $logs = $db->select("SELECT * FROM sms_log ORDER BY id DESC LIMIT 60"); } catch (\Throwable $e) {}

$otps = [];
/* whether a code has run out is worked out by MySQL, so a PHP timezone that
   differs from the database server's cannot make the column read wrong */
try {
    $otps = $db->select(
        "SELECT id, purpose, mobile, attempts, verified, expires_at, created_at, ip_address,
                (expires_at < NOW()) AS is_expired
         FROM otp_codes ORDER BY id DESC LIMIT 40");
} catch (\Throwable $e) {}

$missing = sms_missing();
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SMS &amp; OTP - <?php echo htmlspecialchars($company_name); ?> Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; }
        [x-cloak] { display: none !important; }
        .lbl { display:block; font-size:11px; font-weight:700; color:#475569; margin-bottom:4px; }
        .fld { width:100%; border:1px solid #cbd5e1; border-radius:10px; padding:8px 11px; font-size:13px; background:#fff; }
        .fld:focus { outline:none; border-color:#6366f1; box-shadow:0 0 0 3px rgba(99,102,241,.15); }
        .hint { font-size:10px; color:#94a3b8; margin-top:4px; }
        .chip { display:inline-block; font-family:ui-monospace,monospace; font-size:10px; font-weight:700;
                background:#eef2ff; color:#4338ca; border:1px solid #c7d2fe; border-radius:6px;
                padding:1px 6px; margin:2px 3px 0 0; cursor:pointer; }
        .chip:hover { background:#e0e7ff; }
    </style>
</head>
<body class="bg-gray-50" x-data="smsBoard()" x-cloak>

<div class="flex h-screen overflow-hidden">

    <?php include __DIR__ . '/includes/sidebar.php'; ?>

    <div class="flex-1 flex flex-col min-w-0 bg-gray-100 overflow-hidden">

        <header class="h-20 bg-white flex items-center justify-between px-4 lg:px-8 shadow-sm border-b border-gray-200 z-40 relative flex-shrink-0">
            <div class="flex items-center min-w-0">
                <button @click="sidebarOpen = !sidebarOpen" class="p-2 mr-3 text-slate-500 hover:text-indigo-600 rounded-lg hover:bg-gray-100"><i class="fas fa-bars text-xl"></i></button>
                <div class="min-w-0">
                    <h2 class="text-xl font-bold truncate text-slate-800">SMS &amp; OTP</h2>
                    <p class="text-[11px] text-slate-400 hidden sm:block">The gateway, the codes, and the three messages that go out</p>
                </div>
            </div>
            <div class="flex items-center gap-2">
                <form method="POST"><button type="submit" name="check_balance" value="1" class="hidden sm:inline-flex items-center gap-2 px-4 py-2 rounded-xl bg-white ring-1 ring-slate-200 text-xs font-bold text-slate-600 hover:bg-slate-50"><i class="fas fa-coins"></i> Check credit</button></form>
                <button type="submit" form="smsForm" class="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 text-white text-xs font-bold shadow hover:shadow-lg"><i class="fas fa-check"></i> Save settings</button>
            </div>
        </header>

        <main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8">

            <?php if ($flash_ok): ?>
            <div class="mb-5 bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-xl text-sm"><i class="fas fa-check-circle mr-2"></i><?php echo htmlspecialchars($flash_ok); ?></div>
            <?php endif; ?>
            <?php if ($flash_err): ?>
            <div class="mb-5 bg-rose-50 border border-rose-200 text-rose-700 px-4 py-3 rounded-xl text-sm"><i class="fas fa-circle-exclamation mr-2"></i><?php echo htmlspecialchars($flash_err); ?></div>
            <?php endif; ?>

            <?php if (!empty($missing)): ?>
            <div class="mb-5 bg-amber-50 border border-amber-200 text-amber-800 px-5 py-4 rounded-2xl text-xs">
                <p class="font-bold text-sm mb-1"><i class="fas fa-triangle-exclamation mr-1"></i>Still to fill in: <?php echo htmlspecialchars(implode(', ', $missing)); ?></p>
                <p>Until these are set, no text can leave the site. Leave <b>Test mode</b> on meanwhile — the code
                   shows on the screen instead, so registration and password reset both work today.</p>
                <p class="mt-1">Your <b>Sender ID</b> is the 6-character DLT header from the HSPSMS panel, under
                   <b>Setting &rarr; Sender ID</b>.</p>
            </div>
            <?php elseif ($cfg['sms_test_mode'] === '1'): ?>
            <div class="mb-5 bg-blue-50 border border-blue-200 text-blue-800 px-5 py-4 rounded-2xl text-xs">
                <p class="font-bold text-sm mb-1"><i class="fas fa-flask mr-1"></i>Test mode is on</p>
                <p>Nothing is being texted. Codes appear on the screen so you can walk through the flow yourself.
                   Send a test below, then switch test mode off when you are happy.</p>
            </div>
            <?php endif; ?>

            <!-- ============ COUNTERS ============ -->
            <div class="grid grid-cols-2 lg:grid-cols-5 gap-4 mb-6">
                <?php
                $cards = [
                    ['Sent',          $stats['sent'],      'fa-paper-plane',  'emerald'],
                    ['Failed',        $stats['failed'],    'fa-circle-xmark', 'rose'],
                    ['Held back',     $stats['skipped'],   'fa-flask',        'amber'],
                    ['Today',         $stats['today'],     'fa-calendar-day', 'sky'],
                    ['Codes today',   $stats['otp_today'] . ' / ' . $stats['otp_ok'] . ' ok', 'fa-shield-halved', 'violet'],
                ];
                foreach ($cards as $c): ?>
                <div class="bg-white rounded-2xl border border-slate-200 p-5">
                    <div class="w-10 h-10 rounded-xl bg-<?php echo $c[3]; ?>-100 text-<?php echo $c[3]; ?>-600 flex items-center justify-center mb-3"><i class="fas <?php echo $c[2]; ?>"></i></div>
                    <p class="text-xl font-black text-slate-800"><?php echo $c[1]; ?></p>
                    <p class="text-[11px] font-bold text-slate-400 uppercase tracking-wide"><?php echo $c[0]; ?></p>
                </div>
                <?php endforeach; ?>
            </div>

            <form method="POST" id="smsForm" class="space-y-6">
                <input type="hidden" name="save_sms" value="1">

                <!-- ============ SWITCHES ============ -->
                <div class="bg-white rounded-2xl border border-slate-200 overflow-hidden">
                    <div class="p-5 md:p-6 border-b border-slate-100">
                        <h3 class="text-lg font-extrabold text-slate-800">What is switched on</h3>
                        <p class="text-xs text-slate-400 mt-0.5">Turn any of these off and that part of the site simply stops asking.</p>
                    </div>
                    <div class="p-5 md:p-6 grid grid-cols-1 md:grid-cols-2 gap-4">
                        <?php
                        $switches = [
                            ['sms_enabled',          'Send SMS at all',              'The master switch. Off means nothing is ever texted.', 'fa-tower-broadcast'],
                            ['sms_test_mode',        'Test mode',                    'Nothing is texted; the code shows on the screen instead.', 'fa-flask'],
                            ['otp_register_enabled', 'OTP on registration',          'A new member must confirm their mobile before the account is made.', 'fa-user-plus'],
                            ['otp_reset_enabled',    'Forgot password by mobile OTP','The Mobile OTP tab on the forgot-password screen.', 'fa-mobile-screen'],
                            ['reset_email_enabled',  'Forgot password by email link','The Email link tab on the forgot-password screen.', 'fa-envelope'],
                            ['sms_welcome_enabled',  'Congratulations SMS',          'The welcome text with the new User ID, sent as soon as the account exists.', 'fa-gift'],
                        ];
                        foreach ($switches as $s):
                            $on = ($cfg[$s[0]] === '1'); ?>
                        <label class="flex items-start gap-3 p-4 rounded-xl border cursor-pointer transition-colors <?php echo $on ? 'border-indigo-300 bg-indigo-50/50' : 'border-slate-200 bg-white hover:border-slate-300'; ?>">
                            <input type="checkbox" name="<?php echo $s[0]; ?>" value="1" <?php echo $on ? 'checked' : ''; ?> class="w-4 h-4 mt-0.5 rounded accent-indigo-600 flex-shrink-0">
                            <span class="min-w-0">
                                <span class="block text-sm font-bold text-slate-700"><i class="fas <?php echo $s[3]; ?> text-slate-400 mr-1.5"></i><?php echo $s[1]; ?></span>
                                <span class="block text-[11px] text-slate-400 mt-0.5 leading-relaxed"><?php echo $s[2]; ?></span>
                            </span>
                        </label>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- ============ THE GATEWAY ============ -->
                <div class="bg-white rounded-2xl border border-slate-200 overflow-hidden">
                    <div class="p-5 md:p-6 border-b border-slate-100">
                        <h3 class="text-lg font-extrabold text-slate-800">HSPSMS account</h3>
                        <p class="text-xs text-slate-400 mt-0.5">Straight from your panel at sms.hspsms.com &rarr; Developer API.</p>
                    </div>
                    <div class="p-5 md:p-6 grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="lbl">API address</label>
                            <input type="text" name="sms_api_url" value="<?php echo htmlspecialchars($cfg['sms_api_url']); ?>" class="fld">
                            <p class="hint">Leave this alone unless HSPSMS tell you otherwise.</p>
                        </div>
                        <div>
                            <label class="lbl">Username</label>
                            <input type="text" name="sms_username" value="<?php echo htmlspecialchars($cfg['sms_username']); ?>" class="fld">
                            <p class="hint">The name you sign in to the panel with.</p>
                        </div>
                        <div>
                            <label class="lbl">API key</label>
                            <input type="text" name="sms_apikey" value="<?php echo htmlspecialchars($cfg['sms_apikey']); ?>" class="fld font-mono text-[11px]">
                            <p class="hint">Developer API &rarr; the key in the table.</p>
                        </div>
                        <div>
                            <label class="lbl">Sender ID <span class="text-rose-500">*</span></label>
                            <input type="text" name="sms_sender_id" maxlength="11" value="<?php echo htmlspecialchars($cfg['sms_sender_id']); ?>" class="fld uppercase font-bold" placeholder="WBMCZO">
                            <p class="hint">Your DLT-approved header, 6 characters. Panel &rarr; Setting &rarr; Sender ID. <b>Nothing sends without it.</b></p>
                        </div>
                        <div>
                            <label class="lbl">Message type</label>
                            <select name="sms_type" class="fld">
                                <option value="TRANS"  <?php echo $cfg['sms_type'] === 'TRANS'  ? 'selected' : ''; ?>>TRANS — transactional (OTP, alerts)</option>
                                <option value="PROMO"  <?php echo $cfg['sms_type'] === 'PROMO'  ? 'selected' : ''; ?>>PROMO — promotional</option>
                                <option value="INFORM" <?php echo $cfg['sms_type'] === 'INFORM' ? 'selected' : ''; ?>>INFORM — informational</option>
                            </select>
                            <p class="hint">Keep this on TRANS for codes — they must reach a phone on DND too.</p>
                        </div>
                        <div>
                            <label class="lbl">DLT Entity ID <span class="text-slate-400 font-normal">(optional)</span></label>
                            <input type="text" name="sms_entity_id" value="<?php echo htmlspecialchars($cfg['sms_entity_id']); ?>" class="fld font-mono text-[11px]">
                            <p class="hint">Only if HSPSMS ask you to pass it. Kept here for your own reference.</p>
                        </div>
                    </div>
                </div>

                <!-- ============ THE RULES ============ -->
                <div class="bg-white rounded-2xl border border-slate-200 overflow-hidden">
                    <div class="p-5 md:p-6 border-b border-slate-100">
                        <h3 class="text-lg font-extrabold text-slate-800">How a code behaves</h3>
                        <p class="text-xs text-slate-400 mt-0.5">Tighter numbers mean fewer wasted credits and less room for guessing.</p>
                    </div>
                    <div class="p-5 md:p-6 grid grid-cols-2 lg:grid-cols-5 gap-4">
                        <div>
                            <label class="lbl">Digits in the code</label>
                            <input type="number" name="otp_length" min="4" max="8" value="<?php echo (int)$cfg['otp_length']; ?>" class="fld">
                            <p class="hint">4 to 8</p>
                        </div>
                        <div>
                            <label class="lbl">Valid for (minutes)</label>
                            <input type="number" name="otp_expiry_minutes" min="1" max="60" value="<?php echo (int)$cfg['otp_expiry_minutes']; ?>" class="fld">
                            <p class="hint">10 suits most people</p>
                        </div>
                        <div>
                            <label class="lbl">Wrong tries allowed</label>
                            <input type="number" name="otp_max_attempts" min="1" max="10" value="<?php echo (int)$cfg['otp_max_attempts']; ?>" class="fld">
                            <p class="hint">Then that code is burnt</p>
                        </div>
                        <div>
                            <label class="lbl">Wait before resend (sec)</label>
                            <input type="number" name="otp_resend_seconds" min="0" max="600" value="<?php echo (int)$cfg['otp_resend_seconds']; ?>" class="fld">
                            <p class="hint">Stops credit being burned</p>
                        </div>
                        <div>
                            <label class="lbl">Codes per number a day</label>
                            <input type="number" name="otp_max_per_day" min="0" max="100" value="<?php echo (int)$cfg['otp_max_per_day']; ?>" class="fld">
                            <p class="hint">0 means no limit</p>
                        </div>
                    </div>
                </div>

                <!-- ============ THE MESSAGES ============ -->
                <div class="bg-white rounded-2xl border border-slate-200 overflow-hidden">
                    <div class="p-5 md:p-6 border-b border-slate-100">
                        <h3 class="text-lg font-extrabold text-slate-800">The three messages</h3>
                        <p class="text-xs text-slate-400 mt-0.5">
                            Paste your DLT-approved template word for word. Only the pieces in
                            <span class="chip">{braces}</span> are swapped out — everything else must match what DLT approved,
                            or the operator will reject the text.
                        </p>
                    </div>
                    <div class="p-5 md:p-6 space-y-6">
                        <?php
                        $tpls = [
                            ['sms_tpl_otp_register', 'Registration code',
                             'Goes out when someone signs up and has to confirm their mobile.',
                             ['{otp}', '{minutes}', '{name}', '{company}'], 'fa-user-plus', 'indigo'],
                            ['sms_tpl_otp_reset', 'Password reset code',
                             'Goes out from the Forgot password screen.',
                             ['{otp}', '{minutes}', '{name}', '{company}'], 'fa-key', 'amber'],
                            ['sms_tpl_welcome', 'Congratulations message',
                             'Goes out the moment the account is created, carrying the new User ID.',
                             ['{name}', '{userid}', '{refcode}', '{mobile}', '{company}', '{site}'], 'fa-gift', 'emerald'],
                        ];
                        foreach ($tpls as $t): ?>
                        <div x-data="{ v: <?php echo htmlspecialchars(json_encode($cfg[$t[0]]), ENT_QUOTES); ?> }">
                            <div class="flex items-start justify-between gap-3 flex-wrap mb-2">
                                <div>
                                    <label class="text-sm font-bold text-slate-700">
                                        <i class="fas <?php echo $t[4]; ?> text-<?php echo $t[5]; ?>-500 mr-1.5"></i><?php echo $t[1]; ?>
                                    </label>
                                    <p class="text-[11px] text-slate-400"><?php echo $t[2]; ?></p>
                                </div>
                                <p class="text-[10px] font-bold text-slate-400">
                                    <span x-text="v.length"></span> characters &middot;
                                    <span x-text="Math.max(1, Math.ceil(v.length / 160))"></span> credit(s)
                                </p>
                            </div>
                            <textarea name="<?php echo $t[0]; ?>" x-model="v" rows="3" class="fld font-mono text-[12px] leading-relaxed"><?php echo htmlspecialchars($cfg[$t[0]]); ?></textarea>
                            <div class="mt-2">
                                <span class="text-[10px] font-bold text-slate-400 uppercase mr-1">Click to insert:</span>
                                <?php foreach ($t[3] as $ph): ?>
                                <span class="chip" @click="v += '<?php echo $ph; ?>'"><?php echo $ph; ?></span>
                                <?php endforeach; ?>
                            </div>
                            <div class="mt-3 rounded-xl bg-slate-50 border border-slate-200 p-3">
                                <p class="text-[10px] font-black text-slate-400 uppercase tracking-wider mb-1">What the phone will show</p>
                                <p class="text-[12px] text-slate-700 leading-relaxed" x-text="preview(v)"></p>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </form>

            <!-- ============ TEST SEND ============ -->
            <div id="test" class="bg-white rounded-2xl border border-slate-200 overflow-hidden mt-6">
                <div class="p-5 md:p-6 border-b border-slate-100">
                    <h3 class="text-lg font-extrabold text-slate-800">Try it on your own phone</h3>
                    <p class="text-xs text-slate-400 mt-0.5">The surest way to know the header and the template were accepted.</p>
                </div>

                <?php if ($test_result !== null): ?>
                <div class="mx-5 md:mx-6 mt-5 rounded-xl px-4 py-3 text-xs <?php
                    echo !empty($test_result['skipped']) ? 'bg-amber-50 border border-amber-200 text-amber-800'
                        : ($test_result['ok'] ? 'bg-emerald-50 border border-emerald-200 text-emerald-700'
                                              : 'bg-rose-50 border border-rose-200 text-rose-700'); ?>">
                    <p class="font-bold mb-1">
                        <?php if (!empty($test_result['skipped'])): ?>
                            <i class="fas fa-flask mr-1"></i>Held back — <?php echo htmlspecialchars($test_result['error']); ?>
                        <?php elseif ($test_result['ok']): ?>
                            <i class="fas fa-circle-check mr-1"></i>Sent to <?php echo htmlspecialchars($test_to ?? ''); ?>
                        <?php else: ?>
                            <i class="fas fa-circle-xmark mr-1"></i>It did not go: <?php echo htmlspecialchars($test_result['error']); ?>
                        <?php endif; ?>
                    </p>
                    <?php if (!empty($test_result['msgid'])): ?>
                    <p>Message ID: <span class="font-mono"><?php echo htmlspecialchars($test_result['msgid']); ?></span></p>
                    <?php endif; ?>
                    <?php if (!empty($test_result['response'])): ?>
                    <p class="font-mono text-[10px] mt-1 opacity-80 break-all">Gateway said: <?php echo htmlspecialchars(substr($test_result['response'], 0, 400)); ?></p>
                    <?php endif; ?>
                </div>
                <?php endif; ?>

                <form method="POST" class="p-5 md:p-6 grid grid-cols-1 md:grid-cols-3 gap-4 items-end">
                    <input type="hidden" name="send_test" value="1">
                    <div>
                        <label class="lbl">Your mobile number</label>
                        <input type="tel" name="test_mobile" maxlength="10" pattern="[0-9]{10}" class="fld" placeholder="9876543210" required>
                    </div>
                    <div class="md:col-span-2">
                        <label class="lbl">Message <span class="text-slate-400 font-normal">(leave blank to use the registration template with 123456)</span></label>
                        <input type="text" name="test_message" class="fld" placeholder="Leave blank for the standard OTP text">
                    </div>
                    <div class="md:col-span-3">
                        <button type="submit" class="px-6 py-2.5 rounded-xl bg-slate-800 text-white text-xs font-bold hover:bg-slate-900"><i class="fas fa-paper-plane mr-1"></i> Send a test SMS</button>
                        <span class="text-[11px] text-slate-400 ml-3">Save your settings first — the test uses whatever is stored.</span>
                    </div>
                </form>
            </div>

            <!-- ============ APPROVED DLT WORDING ============ -->
            <?php $dlt_on = (trim((string)$cfg['sms_tpl_otp_register']) === $DLT_REGISTER); ?>
            <div class="bg-white rounded-2xl border border-slate-200 overflow-hidden mt-6">
                <div class="p-5 md:p-6 border-b border-slate-100">
                    <h3 class="text-lg font-extrabold text-slate-800">The wording the operator accepts</h3>
                    <p class="text-xs text-slate-400 mt-0.5">India scrubs every transactional text against the DLT registry. Wording that is not registered is billed and then thrown away.</p>
                </div>
                <div class="p-5 md:p-6">
                    <p class="text-[11px] font-bold text-slate-500 mb-1">Approved under this account's header</p>
                    <pre class="bg-slate-900 text-slate-100 rounded-xl p-3 text-[11.5px] whitespace-pre-wrap">{#var#} is the OTP for {#var#}. Please do not share this OTP with anyone. This SMS has been sent from GuestRAR.</pre>
                    <p class="text-[11px] font-bold text-slate-500 mt-4 mb-1">What the site sends</p>
                    <pre class="bg-slate-100 text-slate-700 rounded-xl p-3 text-[11.5px] whitespace-pre-wrap"><?php echo htmlspecialchars($DLT_REGISTER . "\n\n" . $DLT_RESET); ?></pre>
                    <?php if ($dlt_on): ?>
                        <div class="mt-4 rounded-xl bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 text-xs font-bold">
                            <i class="fas fa-circle-check mr-1"></i> In use — the site is sending the approved wording.
                        </div>
                    <?php else: ?>
                        <form method="POST" class="mt-4">
                            <button type="submit" name="apply_dlt" value="1"
                                    class="px-6 py-2.5 rounded-xl bg-indigo-600 text-white text-xs font-bold hover:bg-indigo-700">
                                <i class="fas fa-wand-magic-sparkles mr-1"></i> Use the approved wording
                            </button>
                            <span class="text-[11px] text-slate-400 ml-3">The welcome SMS is switched off at the same time — it has no template of its own.</span>
                        </form>
                    <?php endif; ?>
                </div>
            </div>

            <!-- ============ DELIVERY REPORT ============ -->
            <div id="dlr" class="bg-white rounded-2xl border border-slate-200 overflow-hidden mt-6">
                <div class="p-5 md:p-6 border-b border-slate-100">
                    <h3 class="text-lg font-extrabold text-slate-800">Did it actually reach the phone?</h3>
                    <p class="text-xs text-slate-400 mt-0.5">"Message SuccessFully Submitted" only means the gateway took it. Paste a message ID from the log below.</p>
                </div>
                <?php if ($dlr !== null): ?>
                <div class="mx-5 md:mx-6 mt-5 rounded-xl px-4 py-3 text-xs <?php echo !empty($dlr['ok'])
                        ? 'bg-emerald-50 border border-emerald-200 text-emerald-700'
                        : 'bg-amber-50 border border-amber-200 text-amber-800'; ?>">
                    <p class="font-bold"><?php echo htmlspecialchars($dlr_id); ?> —
                        <?php echo $dlr['status'] !== '' ? htmlspecialchars($dlr['status']) : 'no status came back'; ?></p>
                    <?php if (!empty($dlr['raw'])): ?>
                    <p class="font-mono text-[10px] mt-1 opacity-80 break-all"><?php echo htmlspecialchars(substr((string)$dlr['raw'], 0, 400)); ?></p>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
                <form method="POST" class="p-5 md:p-6 grid grid-cols-1 md:grid-cols-3 gap-4 items-end">
                    <input type="hidden" name="check_dlr" value="1">
                    <div>
                        <label class="lbl">Message ID</label>
                        <input type="text" name="dlr_msgid" class="fld" placeholder="e.g. 32014896"
                               value="<?php echo htmlspecialchars($dlr_id); ?>" required>
                    </div>
                    <div class="md:col-span-2">
                        <button type="submit" class="px-6 py-2.5 rounded-xl bg-slate-800 text-white text-xs font-bold hover:bg-slate-900"><i class="fas fa-truck-fast mr-1"></i> Check delivery</button>
                    </div>
                    <p class="md:col-span-3 text-[11px] text-slate-400 leading-relaxed">
                        <b class="text-slate-600">DELIVRD</b> reached the handset ·
                        <b class="text-slate-600">UNDELIV / EXPIRED</b> the operator never handed it over, almost always a wording that is not registered ·
                        <b class="text-slate-600">REJECTD</b> refused outright ·
                        <b class="text-slate-600">DND</b> that number blocks promotional traffic ·
                        <b class="text-slate-600">SUBMITTED</b> still queued, ask again in a minute.
                    </p>
                </form>
            </div>

            <!-- ============ THE LOGS ============ -->
            <div class="grid grid-cols-1 xl:grid-cols-2 gap-6 mt-6">

                <div class="bg-white rounded-2xl border border-slate-200 overflow-hidden">
                    <div class="p-5 border-b border-slate-100 flex items-center justify-between gap-3">
                        <div>
                            <h3 class="text-base font-extrabold text-slate-800">Messages that went out</h3>
                            <p class="text-xs text-slate-400 mt-0.5">The last 60</p>
                        </div>
                        <form method="POST" onsubmit="return confirm('Clear everything older than 30 days?');">
                            <input type="hidden" name="purge_logs" value="1">
                            <input type="hidden" name="purge_days" value="30">
                            <button type="submit" class="px-3 py-1.5 rounded-lg bg-rose-50 text-rose-600 ring-1 ring-rose-200 text-[11px] font-bold hover:bg-rose-100"><i class="fas fa-broom mr-1"></i>Clear old</button>
                        </form>
                    </div>
                    <div class="overflow-x-auto max-h-[460px] overflow-y-auto">
                        <table class="w-full text-left text-xs border-collapse">
                            <thead class="sticky top-0">
                                <tr class="bg-slate-50 text-[10px] uppercase text-slate-500 tracking-wider border-b border-slate-200">
                                    <th class="p-3 font-semibold">Number</th>
                                    <th class="p-3 font-semibold">Message</th>
                                    <th class="p-3 font-semibold">Why</th>
                                    <th class="p-3 font-semibold">Result</th>
                                    <th class="p-3 font-semibold">When</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100">
                            <?php if (!empty($logs)): foreach ($logs as $l):
                                $tone = ['sent' => 'bg-emerald-50 text-emerald-600 ring-emerald-200',
                                         'failed' => 'bg-rose-50 text-rose-600 ring-rose-200',
                                         'skipped' => 'bg-amber-50 text-amber-600 ring-amber-200'][$l['status']] ?? 'bg-slate-100 text-slate-500 ring-slate-200'; ?>
                                <tr class="hover:bg-slate-50/70 align-top">
                                    <td class="p-3 font-mono whitespace-nowrap"><?php echo htmlspecialchars($l['mobile']); ?></td>
                                    <td class="p-3 text-slate-500 max-w-[220px]"><span title="<?php echo htmlspecialchars($l['message']); ?>"><?php echo htmlspecialchars(mb_strimwidth((string)$l['message'], 0, 54, '…')); ?></span></td>
                                    <td class="p-3 text-slate-400 whitespace-nowrap"><?php echo htmlspecialchars($l['purpose']); ?></td>
                                    <td class="p-3 whitespace-nowrap">
                                        <span class="inline-block px-2 py-0.5 rounded-md text-[10px] font-bold ring-1 <?php echo $tone; ?>"><?php echo htmlspecialchars($l['status']); ?></span>
                                        <?php if ($l['status'] === 'failed' && !empty($l['response'])): ?>
                                        <p class="text-[10px] text-rose-400 mt-0.5 max-w-[160px] truncate" title="<?php echo htmlspecialchars($l['response']); ?>"><?php echo htmlspecialchars(mb_strimwidth((string)$l['response'], 0, 40, '…')); ?></p>
                                        <?php endif; ?>
                                    </td>
                                    <td class="p-3 text-slate-400 whitespace-nowrap"><?php echo date('d M, h:i A', strtotime($l['created_at'])); ?></td>
                                </tr>
                            <?php endforeach; else: ?>
                                <tr><td colspan="5" class="p-10 text-center text-slate-400">Nothing has been sent yet.</td></tr>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="bg-white rounded-2xl border border-slate-200 overflow-hidden">
                    <div class="p-5 border-b border-slate-100">
                        <h3 class="text-base font-extrabold text-slate-800">Codes asked for</h3>
                        <p class="text-xs text-slate-400 mt-0.5">The last 40 — the codes themselves are hashed and never shown</p>
                    </div>
                    <div class="overflow-x-auto max-h-[460px] overflow-y-auto">
                        <table class="w-full text-left text-xs border-collapse">
                            <thead class="sticky top-0">
                                <tr class="bg-slate-50 text-[10px] uppercase text-slate-500 tracking-wider border-b border-slate-200">
                                    <th class="p-3 font-semibold">Number</th>
                                    <th class="p-3 font-semibold">What for</th>
                                    <th class="p-3 font-semibold">Tries</th>
                                    <th class="p-3 font-semibold">Outcome</th>
                                    <th class="p-3 font-semibold">When</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100">
                            <?php if (!empty($otps)): foreach ($otps as $o):
                                $done = (int)$o['verified'] === 1;
                                $dead = !$done && (int)($o['is_expired'] ?? 0) === 1; ?>
                                <tr class="hover:bg-slate-50/70">
                                    <td class="p-3 font-mono whitespace-nowrap"><?php echo htmlspecialchars($o['mobile']); ?></td>
                                    <td class="p-3 text-slate-500"><?php echo htmlspecialchars($o['purpose']); ?></td>
                                    <td class="p-3 text-slate-400"><?php echo (int)$o['attempts']; ?></td>
                                    <td class="p-3 whitespace-nowrap">
                                        <span class="inline-block px-2 py-0.5 rounded-md text-[10px] font-bold ring-1 <?php
                                            echo $done ? 'bg-emerald-50 text-emerald-600 ring-emerald-200'
                                                : ($dead ? 'bg-slate-100 text-slate-500 ring-slate-200'
                                                         : 'bg-sky-50 text-sky-600 ring-sky-200'); ?>">
                                            <?php echo $done ? 'confirmed' : ($dead ? 'expired' : 'waiting'); ?>
                                        </span>
                                    </td>
                                    <td class="p-3 text-slate-400 whitespace-nowrap"><?php echo date('d M, h:i A', strtotime($o['created_at'])); ?></td>
                                </tr>
                            <?php endforeach; else: ?>
                                <tr><td colspan="5" class="p-10 text-center text-slate-400">No codes yet.</td></tr>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<script>
function smsBoard() {
    return {
        sidebarOpen: window.innerWidth >= 768,
        preview(t) {
            return (t || '')
                .replace(/\{otp\}/g,     '<?php echo str_repeat("9", max(4, min(8, (int)$cfg["otp_length"]))); ?>')
                .replace(/\{minutes\}/g, '<?php echo (int)$cfg["otp_expiry_minutes"]; ?>')
                .replace(/\{name\}/g,    'Rahul Das')
                .replace(/\{userid\}/g,  'WBMCZ0042')
                .replace(/\{refcode\}/g, 'WBMCZ0042')
                .replace(/\{mobile\}/g,  '9876543210')
                .replace(/\{company\}/g, <?php echo json_encode($company_name); ?>)
                .replace(/\{site\}/g,    <?php echo json_encode(defined('SITE_URL') ? SITE_URL : ''); ?>);
        }
    };
}
</script>

</body>
</html>
